Angular 5.x将包含新的StaticInjector,如
in this tweet所述.我有两个问题:
>它与现有的ReflectiveInjector有何不同?
>它会破坏我现有的代码吗?
解决方法
首先,有一篇很棒的文章
Angular introduces StaticInjector. Should you care?解释了细节上的差异.
How is it different from existing ReflectiveInjector?
ReflectiveInjector
依靠Reflect库提供的反射功能来提取提供者的隐式依赖关系,因此名称为Reflective:
class B {} class A { constructor(@Inject(B) b) { } <----- `B` is implicit dependency } const i = ReflectiveInjector.resolveAndCreate([A,B]);
@Inject装饰器定义指定隐式依赖关系的元数据,ReflectiveInjector使用此元数据.
StaticInjector
不使用反射功能并且需要明确指定依赖项:
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.