如何为每个子组件提供实例? [英] How to provide an instance oer each child component?

查看:67
本文介绍了如何为每个子组件提供实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经熟悉了依赖注入在Angular 2中的工作原理,但是我试图弄清楚是否可以使用特定的用例。

I'm getting familiar with how dependency injection works in Angular 2, but I'm trying to figure out if a specific use case is possible.

总之我想拥有一个注入了依赖项的子组件,如下所示:

In short I'd like to have a child component that has a dependency injected like so:

@Component( {
    selector: 'child',
    template: `
        <div class="child">
            <span><a href="#" (click)="idService.regenerate()">Regenerate</a></span>
            <span>{{idService.id}}</span>
        </div>
    `
})
export class ChildComponent {

    constructor(
        protected idService: IdService
    )
    {}
}

在组件树的更高级别上,我使用提供程序:[IdService] 注入服务的不同实例。这一切都是有道理的,不会给我带来任何问题。但是,我想了解的是,是否有可能在不创建带有自己的提供者:[...] 属性的子组件的副本的情况下组件注释:

At higher levels of my component tree I am using providers: [IdService] to inject different instances of the service. This all makes sense and doesn't give me a problem. However, what I'd like to understand is if this is possible without creating a "copy" of the child component with its own providers: [...] property in the component annotation:

https:// plnkr.co/edit/ZMYNIH7lB0Oi6EBSYmfB?p=preview

在该示例中,您将看到底部的每个组件都获得了 IdService 类,但这是因为它们确实是一个专门请求新实例的新组件。

In that example you'll see the bottom set of components each get a new instance of the IdService class, but it's because they're really a new component that specifically requests a new instance.

我要做什么d想知道是否有一种方法可以简单地通过父组件来实现?就像能够说每次子组件尝试解决此特定依赖性时都给新实例一样?

What I'd like to know is if there's a way to achieve this simply with the parent component? Like being able to say "give a new instance each time a child component tries to resolve this specific dependency"?

推荐答案

如果组件在其关联的注入器中找到提供程序,它将使用它来获取/创建服务。 。如果不是,它将查看父注入器(与父组件关联的注入器),依此类推。这是从底部到顶部,而不是从顶部到底部。

If a component finds a provider within its associated injector, it will use it to get / create the service. If not it will have a look at the parent injector (the injector associated with the parent component) and so on. This is done from the bottom to the top and not the top to the bottom.

如果在父组件中找到提供者,则所有子代将使用相同的实例,因为

If the provider is found in the parent component, all children will use the same instance since the latter is a singleton at this level.

有关分层注入器的更多详细信息,请参见此问题:

See this question for more details about hierarchical injectors:

  • What's the best way to inject one service into another in angular 2 (Beta)?

这篇关于如何为每个子组件提供实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆