Search code examples
angulardependency-injectionangular2-services

Angular2 services dependency injection


When AuthService => login is called, the logger correctly appends Foo! in the browser console but when ErroHandler => handleError is called, the instance of the logger is always undefined (except in the constructor of the class). I expected to see Bar! also beeing appended in the browser console. Can anyone explain me this behaviour?

Reference: https://embed.plnkr.co/cKwT5R39IL1TTJBRvZyY/


Solution

  • The problem has nothing to do with dependency injection. If DI problem occurs, this results in error message from compiler.

    This happens because errorHandler.handleError method is passed as a callback here:

    .catch(this.errorHandler.handleError);
    

    and isn't bound correctly to the context.

    This is a typical mistake. Unless it is known that object method was bound on object construction (this is a good habit for methods that are supposed to be used as callbacks by design), it always should be like

    .catch(err => this.errorHandler.handleError(err));