-1

我已经看到了看起来像旧的 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?

4

1 回答 1

3

@Inject(SomeClass)如果您没有提供它并且您使用类作为参数的类型,则会在编译阶段自动添加。在某些情况下,您需要注入不是类实例的东西。@Inject在这种情况下,没有装饰器就不可能注入东西。例如配置对象:

const someConfigObject: ConfigInterface = {...};
...
providers: [
   {provide: MY_CONFIG_TOKEN, useValue: someConfigObject}
]
....
class MyComponent {
   constructor(@Inject(MY_CONFIG_TOKEN) config: ConfigInterface){}
}
于 2020-12-29T19:23:29.157 回答