简体   繁体   中英

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/

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM