创建动态组件时如何提供自定义服务实例

问题描述

在使用组件工厂解析器动态创建组件时,我想注入已经创建的服务实例。

假设我有 2 个组件

  1. 多选
  2. 数据输入

这些组件有自己的服务(组件特定的服务,不是在模块级别提供的)。

@Component({
  selector: "app-data-entry",templateUrl: "./data-entry.component.html",styleUrls: ["./data-entry.component.css"],providers: [DataEntryService,MultipleChoiceService]
})
export class DataEntryComponent {
  constructor(
    private injector: Injector,private dataEntryService: DataEntryService,private componentFactoryResolver: ComponentFactoryResolver
  ) {}

  @ViewChild("dynTypeHost",{ read: ViewContainerRef })
  dynTypeHost: ViewContainerRef;

  get source(): string {
    return this.dataEntryService.multipleChoiceService.source;
  }

  onLoadMultipleChoiceClick() {
    const resolver = this.componentFactoryResolver.resolveComponentFactory(
      MultipleChoiceComponent
    );
    const injector = Injector.create({
      parent: this.injector,providers: [
        {
          provide: MultipleChoiceService,useValue: this.dataEntryService.multipleChoiceService
        }
      ]
    });
    this.dynTypeHost.createComponent(resolver,injector);
  }
}

如果您看到方法 onLoadMultipleChoiceClick 它具有自定义注入器,我想传递由该组件创建的多项选择服务的实例,但它没有按预期工作。

你可以在这里看到演示

https://stackblitz.com/edit/angular-ivy-vnr7mx?file=src/app/data-entry/data-entry.component.ts

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)