@Injectable. For more information on Decorators please see the EcmaScript 6 and TypeScript Features section.
@Inject()is a manual mechanism for letting Angular know that a parameter must be injected. It can be used like so:
chatWidgetto be the singleton Angular associates with the
@Inject(ChatWidget). It's important to note that we're using
ChatWidgetfor its typings and as a reference to its singleton. We are not using
ChatWidgetto instantiate anything, Angular does that for us behind the scenes.
@Injectis only needed for injecting primitives. TypeScript's types let Angular know what to do in most cases. The above example would be simplified in TypeScript to:
@Injectable()lets Angular know that a class can be used with the dependency injector.
@Injectable()is not strictly required if the class has other Angular decorators on it or does not have any dependencies. What is important is that any class that is going to be injected with Angular is decorated. However, best practice is to decorate injectables with
@Injectable(), as it makes more sense to the reader.
ChatWidgetmarked up with
ChatWidget's constructor by using type information. This is possible because these particular dependencies are typed, and are not primitive types. In some cases Angular's DI needs more information than just types.