7

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.

  • empty is a function and you need to actually call it to get an actual observable: return Observable.empty(); – Brandon Apr 26 '16 at 13:20
  • 1
    You can also use arrow functions .catch((err) => this.handleError(err)) – Günter Zöchbauer Apr 26 '16 at 15:44
  • I found arrow functions to be a much cleaner approach to be able to use this, compared to bind. – Joao May 13 '16 at 14:35
6

I guess this does what you want:

private handleError = (error: any) => {
   this._router.navigate(['Login']);
   return Observable.of([]);
}
|improve this answer|||||
  • I'm doing just this, I also tried return Observable.empty() but I still get Cannot read property 'subscribe' of undefined. I'm not sure if this has to do with the component being destroyed??? – Joao May 13 '16 at 14:39
  • @Joao This doesn't sound related. I guess it's better to create a new question with the code that demonstrates what you have tried. – Günter Zöchbauer May 13 '16 at 14:45
  • Thanks. posted stackoverflow.com/questions/37213494/… – Joao May 13 '16 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.