【问题标题】:In Angular >= 7, is there any advantage to using @Inject over declaring a class @Injectable?在 Angular >= 7 中,使用 @Inject 比声明类 @Injectable 有什么优势吗?
【发布时间】:2020-12-29 18:58:35
【问题描述】:

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

【问题讨论】:

    标签: angular dependency-injection service injectable


    【解决方案1】:

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

    const someConfigObject: ConfigInterface = {...};
    ...
    providers: [
       {provide: MY_CONFIG_TOKEN, useValue: someConfigObject}
    ]
    ....
    class MyComponent {
       constructor(@Inject(MY_CONFIG_TOKEN) config: ConfigInterface){}
    }
    

    【讨论】:

    • 如果@Inject 是自动添加的,有没有需要自己手动添加的情况?在上面的示例中,如果您没有添加“@Inject”,由于您将“MY_CONFIG_TOKEN”指定为提供程序,事情是否会以同样的方式工作?
    • 如果你尝试离开constructor(config: ConfigInterface),那么Angular 会尝试将其转换为constructor(@Inject(ConfigInterface) config: ConfigInterface)。但是运行时没有ConfigInterface 引用。在组件内部,Angular 无法知道您要注入 MY_CONFIG_TOKEN,除非程序员明确指出这一点
    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2020-10-02
    • 2014-02-12
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多