angular 2 - Injected service in http error handler
Asked Answered
A

3

5

I have a method handleError() like in the documentation https://angular.io/docs/ts/latest/guide/server-communication.html#!#error-handling

private handleError(error: any) {
    console.error(error);
    console.log(this.loginService); // <- always undefined
    return Observable.throw(error);
}

My problem is, that this.loginService is undefined although it has been injected in my class correctly. It is already used in other methods but seems not to be available in handleError.

Could the way the method is called by the http-catch be the problem? If so, how can i come around that? I need to execute some logic when handling an error.

This is an example on how i set handleError method as callback (exactly like documentation)

this.http.get(url,
              ApiRequest.ACCEPT_JSON)
              .map(ApiHelper.extractData)
              .catch(this.handleError);
Alfons answered 23/6, 2016 at 10:17 Comment(4)
Do you pass the loginService to the class constructor?Kal
Yep. I am already using it in other methods in the same class.Alfons
Could you show us how you call handleError in your catch?Lovato
I updated my question.Alfons
L
21

Since you're passing the function directly, you don't have the this context of your class in there. A really easy and best practice way would be to use a lambda or "fat arrow function":

this.http.get(url, ApiRequest.ACCEPT_JSON)
    .map(res => ApiHelper.extractData(res))
    .catch(err => this.handleError(err));

A really good read on when to use lambdas: https://mcmap.net/q/25324/-when-should-i-use-arrow-functions-in-ecmascript-6

Lovato answered 23/6, 2016 at 11:57 Comment(0)
O
5

this in handleError in your case is probably not what you think it is.

Try to do the following:

this.http.get(url,
              ApiRequest.ACCEPT_JSON)
              .map(ApiHelper.extractData) 
              .catch(this.handleError.bind(this)); // <-- add .bind(this)
Offprint answered 23/6, 2016 at 11:54 Comment(0)
M
0

Possible solution is also to assign your service to static variable of class

ClassToHandleError {
   private static loginService: LoginService;

   constructor(private loginService: LoginService) {
      ClassToHandleError.loginService = loginService;
   }

   private handleError(error: any) {
    console.error(error);
    console.log(ClassToHandleError.loginService); // here you can use static reference
    return Observable.throw(error);
   }
}

I know this is just workaround and rinukkusu provided definetely better solution then me. I used it until I get through this question. But maybe in some special case this will be valuable for somebody :) .

Menken answered 30/9, 2020 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.