【问题标题】:StaticInjector vs ReflectiveInjector in AngularAngular 中的 StaticInjector 与 ReflectiveInjector
【发布时间】:2017-08-09 08:37:10
【问题描述】:

Angular 5.x 将包含新的StaticInjector,正如提到的in this tweet。我有两个问题:

  • 它与现有的 ReflectiveInjector 有何不同?
  • 它会破坏我现有的任何代码吗?

【问题讨论】:

    标签: angular dependency-injection angular-di


    【解决方案1】:

    首先,有一篇很棒的文章 Angular introduces StaticInjector. Should you care? 详细解释了差异。

    它与现有的 ReflectiveInjector 有何不同?

    反射式注射器

    依靠Reflect库提供的反射能力来提取提供者的隐式依赖,因此得名Reflective:

    class B {}
    class A {
      constructor(@Inject(B) b) { } <----- `B` is implicit dependency
    }
    
    const i = ReflectiveInjector.resolveAndCreate([A, B]);
    

    @Inject 装饰器定义了指定隐式依赖关系的元数据,ReflectiveInjector 使用此元数据。

    静态注射器

    不使用反射功能,需要明确指定依赖关系:

    class B {}
    class A { constructor(b) {} }
    const i = Injector.create([{provide: A, useClass: A, deps: [B]]};
    const a = i.get(A);
    

    它会破坏我现有的任何代码吗? 此更改只会影响提供给平台和编译器提供程序的提供程序。因此,如果您像这样提供它们:

    class B1 {}
    class A1 { constructor(@Inject(B1) b) {} }
    
    class B2 {}
    class A2 { constructor(@Inject(B2) b) {} }
    bootstrapModule(AppModule, {providers: [A1, B1]}).platformBrowserDynamic([A2, B2])
    

    您现在应该将其更改为:

    class B1 {}
    class A1 { constructor(b) {} }
    
    class B2 {}
    class A2 { constructor(b) {} }
    
    platformBrowserDynamic([{ provide: A1, useClass: A1, deps: [B1] }, B1])
    .bootstrapModule(AppModule, { providers: [ {provide: A2, useClass: A2, deps: [B2]}, B2 ] })
    

    ReflectiveInjector 仍被标记为稳定,因此您可能可以继续使用它。但是将来它很有可能会被删除。我建议你尽快开始使用StaticInjector。

    【讨论】:

    • 让我们退后一步。我为什么要首先使用bootstrapModule(AppModule, { providers: [... 和platformBrowserDynamic([{ provide:?你能提供示例代码吗?
    • @RoyiNamir,如果您想在平台级别定义自定义提供程序。这主要由 webworker 和 Universal 等其他平台使用
    • 链接失效
    猜你喜欢
    • 2020-08-28
    • 2020-02-14
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多