以下是来自Heroes Tutorial服务部分的Angular.io网站的解释.
Appendix: Shadowing the parent’s service
We stated earlier that if we injected the parent AppComponent
HeroService into the HeroDetailComponent,we must not add a providers
array to the HeroDetailComponent Metadata.Why? Because that tells Angular to create a new instance of the
HeroService at the HeroDetailComponent level. The HeroDetailComponent
doesn’t want its own service instance; it wants its parent’s service
instance. Adding the providers array creates a new service instance
that shadows the parent instance.Think carefully about where and when to register a provider.
Understand the scope of that registration. Be careful not to create a
new service instance at the wrong level.
Here’s the link到这个来自的页面把它放在上下文中.
解决方法
@SkipSelf()
请考虑以下代码
class Service { someProp = 'Default value'; } @Component({ providers : [Service] // Child's instance }) class Child { constructor( @SkipSelf() parentSvc: Service,svc: Service ) { console.log(pSvc.someProp); // Prints 'Parents instance' console.log(svc.someProp); // Prints 'Default value' } } @Component({ providers : [Service] // Parent's instance }) class Parent { constructor(svc: Service) { svc.someProp = 'Parent instance'; } }
使用@SkipSelf(),我们告诉组件从父注入器启动依赖项解析(SkipSelf这个名称说了很多,我猜).
您可以从@PascalPrecht了解更多关于Host and Visibility in Angular 2’s Dependency Injection的可见性的信息.
用一个工作示例检查这个plnkr.