Angular 2.如何处理4XX错误与重定向在Observable? [英] Angular 2. How to handle 4xx errors with redirect in Observable?

查看:169
本文介绍了Angular 2.如何处理4XX错误与重定向在Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫api的服务

I have a service that calls an api

getItems(itemId: number): Observable<any> {
    return this.http.get(url, headers)
        .map(this.extractDataSingle)
        .catch(this.handleError)
}

如果服务器用4xx响应,调用 catch 部分。
这是我的 handleError 方法。

If the server responds with an 4xx the catch part is called. Here is my handleError method.

private handleError = (error: any) => {
    //Here I want to redirect to login.
}

我想重定向到登录页面。
只需键入 this._router.navigate(['Login']); 不起作用,因为我必须返回一个 Observable
返回一个空的Observable return Observable.empty; 也不起作用,因为我的订阅者收到错误:无法读取属性'subscribe'未定义

I want to redirect to the login page. Simply typing this._router.navigate(['Login']); does not work since I have to return a Observable. Returning an empty Observable return Observable.empty; does not work, too, because then I get an error with my subscribers: Cannot read property 'subscribe' of undefined.

如何实现我将用户重定向到登录页面?当然,我可以更改订阅者以捕获错误并通过订阅者进行重定向。但是,我认为最好处理我的服务中的错误。

How can I achieve that I redirect the user to the login page? Of course I can change my subscribers to catch the error and redirect via my subscribers. But I think it is better to handle the error in my service.

我也对完全不同的解决方案开放了如何处理4xx错误。

I'm also open for completely different solutions of how to handle 4xx errors.

编辑:
感谢@GüntherZöschbauer。 返回Observable.of([]); 正是我需要的。
但是,请注意这个。为了访问 handleError 方法中的路由器使用 bind(this) in .catch(this.handleError.bind(this))

Thanks to @GüntherZöschbauer. The return Observable.of([]); is exactly what I needed. However, be aware of this. In order to have access to the router in the handleError method use bind(this) in .catch(this.handleError.bind(this))

getItems(itemId: number): Observable<any> {
    return this.http.get(url, headers)
        .map(this.extractDataSingle)
        .catch(this.handleError.bind(this))
}

否则您无法访问路由器

推荐答案

我想这是你想要的:

private handleError = (error: any) => {
   this._router.navigate(['Login']);
   return Observable.of([]);
}

这篇关于Angular 2.如何处理4XX错误与重定向在Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆