I have seen what seem like older Angular examples in which dependency injection is done using the "@Inject" annotation ...
import { Component, Inject } from '@angular/core';
import { ChatWidget } from '../components/chat-widget';
@Component({
selector: 'app-root',
template: `Encryption: {{ encryption }}`
})
export class AppComponent {
encryption = this.chatWidget.chatSocket.encryption;
constructor(@Inject(ChatWidget) private chatWidget) { }
}
In later versions of Angular (>= 7), is @Inject still needed if the thing being injected is annotated with @Injectable, e.g.
@Injectable({
providedIn: 'root',
})
export class ChatWidget {
I guess what I'm asking is with later versions of Angular, is there any reason to still be using @Inject?
@Inject(SomeClass)
is added automatically during compilation phase if you didn't provide it and you are using class as type for your parameter. There are still situations where you need to inject something that is not instance of a class. In this case it is impossible to inject the thing without @Inject
decorator. for example config object:
const someConfigObject: ConfigInterface = {...};
...
providers: [
{provide: MY_CONFIG_TOKEN, useValue: someConfigObject}
]
....
class MyComponent {
constructor(@Inject(MY_CONFIG_TOKEN) config: ConfigInterface){}
}