【问题标题】:InjectionToken vs InjectableInjectionToken vs Injectable
【发布时间】:2021-05-11 15:30:26
【问题描述】:

我只是对 InjectionToken 和 Injectable 之间的差异和不同用例感到好奇。我有一个类似下面的服务:


// Service defintion:

export const MY_SERVICE_TOKEN = new InjectionToken<IMyService>('My Service', {
  factory: () => new MyService(),
  providedIn: 'root'
});

export interface IMyService {
  readonly subject: BehaviorSubject<string>;
}


export MyService implements IMyService {
  constructor() {}
  subject: BehaviorSubject<string> = new BehaviorSubject<string>('initial value')
}

// Usage case:
@Component(/* Removed for Brevity */)
export class MyComponent {
  constructor(@Inject(MY_SERVICE_TOKEN) private myService: IMyService) {
  }
}

最初,我的服务类上有 @Injectable 指令和 providedIn: 'root' 属性集。但出于好奇,我最终将其删除,DI 仍然运行良好。从逻辑上讲,这是有道理的,因为我不是通过令牌注入类而是注入接口。所以我的问题是,我还应该在课堂上添加 Injectable 指令吗?或者如果这样做会注册两个服务?一个是用 Injectable 装饰的类,一个是通过 Token 注册的接口?

在什么情况下我会使用 Injectable 而不是 InjectionToken?

如果我不能在接口上定义 Injectable 作为 useClass 属性,还有一个额外的问题?为什么要将服务装饰为 Injectable 以仅通过 useClass 返回不同的类型?和抽象类有关吗?

【问题讨论】:

    标签: angular angular8


    【解决方案1】:

    只是为了给这个帖子一个答案:

    当您提供In: root 时,您将在整个应用程序中提供此资源。

    当您在组件或模块中使用 @Inject 时,此资源将仅存在于应用程序的这些级别。

    On this official documentation你可以找到非常有用的信息

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2019-01-19
      • 2018-10-19
      • 2020-10-27
      相关资源
      最近更新 更多