加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Angular 2.0中注入服务提供者

发布时间:2020-12-17 17:54:01 所属栏目:安全 来源:网络整理
导读:在AngularJS 2.0 Heroes教程解释中,它指出如果子组件在其@Component Providers列表中包含服务,则Angular将创建特定于该子组件的该服务的单独实例.我不明白的是,如果有时您想独立使用子组件,而有时在父组件中使用子组件,您会怎么做.这似乎是一个严重的限制.我
在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读