如何使用Angular2将服务注入动态组件 [英] How to inject a service into a dynamic component with Angular2

查看:241
本文介绍了如何使用Angular2将服务注入动态组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,可以使用DynamicComponentLoader动态加载另一个组件.但是,动态组件需要注入服务.但是,我不确定该怎么做.我从Angular.io文档中看到DynamicComponentLoader接受ResolvedProvider数组.

I have a component that dynamically loads another component using DynamicComponentLoader. However, the dynamic component needs to have a service injected. However, I'm unsure how to go about this. I see from Angular.io docs that DynamicComponentLoader accepts a ResolvedProvider array.

我试图通过以下方式获得提供者:

I've tried to get a provider by doing:

var provider = provide(ManagerService, {useExisting: ManagerService});
dcl.loadIntoLocation(this.data.template, this.er, "content",[provider]);

这似乎不起作用.您可以在插件上看到示例.

This doesn't seem to work. You can see an example on plunker.

在插件示例中,您可以看到Info组件已加载(因为它不需要该服务),但是Alternate组件却未加载.

On the plunker example, you can see that the Info component loads (because it isn't requiring the service) but the Alternate component won't load.

我有点困惑,因为该服务是在根组件上注入的,所以我认为在需要该子组件时,它将自动注入到每个子组件上.

I'm a little confused because the service is being injected at the root component so I thought that it would automatically be injected on every child component when it was called for.

如何注入此服务?

推荐答案

与常规DI没什么不同

this.dynamicComponentLoader.loadIntoLocation(MyComponent, this.elementRef, "content")


class MyComponent{
  constructor(someService:SomeService){}//injected here when instantiated
}

如果动态加载的组件将服务注入构造函数中,则其工作方式与普通DI相同.

If your dynamically loaded component injects services in the constructor it works like normal DI.

但是请确保该服务已在某个提供程序数组中注册.在组件级别或更高级别的链中(父级或自举)

Make sure the service is registered in some provider array though. Either at the component level or higher up in the chain (parent or bootstrap)

这篇关于如何使用Angular2将服务注入动态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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