Angular 中的 StaticInjector 与 ReflectiveInjector

StaticInjector vs ReflectiveInjector in Angular

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

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

How is it different from existing 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);

Will it break any of my existing code? The change will only affect providers supplied to platform and compiler providers. So if you provided them like this:

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