在 Angular 2.0 中注入服务提供者

Injecting Service Providers in Angular 2.0

在 AngularJS 2.0 Heroes 教程解释中指出,如果 child 组件在其 @Component Providers 列表中包含一个服务,那么 Angular 将创建一个单独的实例该服务特定于 child。我不明白的是,如果有时您想独立使用 child 组件,而其他时候想在 parent 组件中使用,您会怎么做。这似乎是一个严格的限制。我刚玩 Angular 2.0,所以很可能我误解了什么。

这是英雄教程服务部分 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