Angular 如何将父组件服务注入到动态组件中?
我使用Angular 8,并动态创建了组件。我将服务的父组件放入提供者数组中。如何将父Angular 如何将父组件服务注入到动态组件中?,angular,angular-dynamic-components,angular-dependency-injection,Angular,Angular Dynamic Components,Angular Dependency Injection,我使用Angular 8,并动态创建了组件。我将服务的父组件放入提供者数组中。如何将父MyService的相同实例注入到动态组件中?如果没有动态组件,我可以通过将该服务注入子组件的构造函数来实现它。但是我如何使用动态组件来实现它呢?下面是创建动态组件的代码 @Component({ selector: 'app-parent', templateUrl: './parent.component.html', providers: [MyService], }) expor
MyService
的相同实例注入到动态组件中?如果没有动态组件,我可以通过将该服务注入子组件的构造函数来实现它。但是我如何使用动态组件来实现它呢?下面是创建动态组件的代码
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
providers: [MyService],
})
export class ParentComponent {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private myService: MyService,
) {
}
createDynamicComponent() {
const injector: Injector = Injector.create({
providers: [
{
provide: MAT_DATE_FORMATS,
useValue: getMatDateFormat(this.dateFormat),
},
],
})
this.dynamicPlaceholder.clear()
const componentFactory = this.componentFactoryResolver
.resolveComponentFactory(DynamicComponent)
const componentRef = this.dynamicPlaceholder
.createComponent(componentFactory, 0, injector)
}
}
问题在于这些方面:
const injector: Injector = Injector.create({
providers: [
{
provide: MAT_DATE_FORMATS,
useValue: getMatDateFormat(this.dateFormat),
},
],
})
我从头创建了一个动态组件注入器。所以它对母注射器一无所知。因此-不了解父提供者。
我需要做的就是将父项
参数添加到喷油器。创建
功能:
const injector: Injector = Injector.create({
providers: [
{
provide: MAT_DATE_FORMATS,
useValue: getMatDateFormat(this.dateFormat),
},
],
parent: this.injector
})
其中此.injector
被注入父组件的构造函数中:
constructor(private injector: Injector) {
}