Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 395
Rose Nettoyeur Avatar asked Apr 26 '16 09:04

Rose Nettoyeur


1 Answers

I guess this does what you want:

private handleError = (error: any) => {
   this._router.navigate(['Login']);
   return Observable.of([]);
}
like image 79
Günter Zöchbauer Avatar answered Nov 15 '22 21:11

Günter Zöchbauer