问题描述
我看到过一些看起来像旧的 Angular 示例,其中使用“@Inject”注释完成依赖注入...
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) { }
}
在更高版本的 Angular (>= 7) 中,如果被注入的东西用@Injectable 注释,是否仍然需要@Inject,例如
@Injectable({
providedIn: 'root',})
export class ChatWidget {
我想我要问的是更高版本的 Angular,还有什么理由继续使用 @Inject?
解决方法
@Inject(SomeClass)
会在编译阶段自动添加,如果您没有提供它并且您使用类作为参数的类型。在某些情况下,您需要注入不是类实例的内容。在这种情况下,不可能在没有 @Inject
装饰器的情况下注入事物。例如配置对象:
const someConfigObject: ConfigInterface = {...};
...
providers: [
{provide: MY_CONFIG_TOKEN,useValue: someConfigObject}
]
....
class MyComponent {
constructor(@Inject(MY_CONFIG_TOKEN) config: ConfigInterface){}
}