gpt4 book ai didi

angular - 在 Angular 2.0 中注入(inject)服务提供者

转载 作者:太空狗 更新时间:2023-10-29 17:31:18 26 4
gpt4 key购买 nike

在 AngularJS 2.0 Heroes 教程解释中指出,如果一个子组件在其 @Component Providers 列表中包含一个服务,那么 Angular 将创建该服务特定于该子组件的单独实例。我不明白的是,如果有时您想独立使用子组件,而其他时候想在父组件中使用,您会怎么做。这似乎是一个严格的限制。我刚玩过 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() 我们告诉组件从父注入(inject)器开始依赖项解析(我猜 SkipSelf 这个名字说明了很多)。

您可以在 Host and Visibility in Angular 2's Dependency Injection 中阅读更多关于可见性的信息来自@PascalPrecht。

检查这个plnkr有一个工作示例。

关于angular - 在 Angular 2.0 中注入(inject)服务提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com