在Angular 2.0中注入服务提供者

前端之家收集整理的这篇文章主要介绍了在Angular 2.0中注入服务提供者前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在AngularJS 2.0 Heroes教程解释中,它指出如果子组件在其@Component Providers列表中包含服务,则Angular将创建特定于该子组件的该服务的单独实例.我不明白的是,如果有时您想独立使用子组件,而有时在父组件中使用子组件,您会怎么做.这似乎是一个严重的限制.我刚刚玩Angular 2.0,所以很可能我误解了一些东西.

以下是来自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到这个来自的页面把它放在上下文中.

解决方法

如果您希望Component拥有自己的服务实例,同时拥有其父服务的实例,则必须查看 @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.

猜你在找的Angularjs相关文章