-1

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?

satish
  • 703
  • 5
  • 23
  • 52

1 Answers1

3

@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){}
}
Andrei
  • 10,117
  • 13
  • 21
  • If @Inject is added automatically, is there ever a case where you would need to manually add it yourself? In the above example, if you hadn't added "@Inject", would things work the same way because you specified "MY_CONFIG_TOKEN" as a provider? – satish Dec 29 '20 at 19:53
  • if you try to leave `constructor(config: ConfigInterface)` then Angular would try to convert it to `constructor(@Inject(ConfigInterface) config: ConfigInterface)`. But there is no `ConfigInterface` reference on runtime. inside of a component there is no way for angular to know that you want to inject MY_CONFIG_TOKEN, without pointing that out explicitly by the programmer – Andrei Dec 29 '20 at 20:03