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

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

问题描述

我有一个调用 api 的服务

getItems(itemId: number): Observable{返回 this.http.get(url, headers).map(this.extractDataSingle).catch(this.handleError)}

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

private handleError = (error: any) =>{//这里我想重定向到登录.}

我想重定向到 login 页面.简单地输入 this._router.navigate(['Login']); 不起作用,因为我必须返回一个 Observable.返回一个空的 Observable return Observable.empty; 也不起作用,因为这样我的订阅者就会收到一个错误:无法读取未定义的属性订阅".>

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

对于如何处理 4xx 错误的完全不同的解决方案,我也持开放态度.

感谢@GüntherZöschbauer.return Observable.of([]); 正是我所需要的.但是,请注意this.为了访问 handleError 方法中的 router 使用 bind(this).catch(this.handleError.bind(这个))

getItems(itemId: number): Observable{返回 this.http.get(url, headers).map(this.extractDataSingle).catch(this.handleError.bind(this))}

否则您将无法访问您的路由器.

解决方案

我想这符合您的要求:

private handleError = (error: any) =>{this._router.navigate(['登录']);返回 Observable.of([]);}

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)
}

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.
}

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.

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

EDIT: 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))
}

Otherwise you don't have access to your router.

解决方案

I guess this does what you want:

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

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

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