Angular 2. How to handle 4xx errors with redirect in Observable?

China☆狼群 提交于 2019-12-18 16:45:12

问题


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.


回答1:


I guess this does what you want:

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


来源:https://stackoverflow.com/questions/36861413/angular-2-how-to-handle-4xx-errors-with-redirect-in-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!