不推荐使用Create:从v5开始,使用新的签名Injector.create(options)(不推荐使用)

时间:2019-05-12 04:38:28

标签: angular dependency-injection

我有一个TabService,可将标签页插入mat-tab-groups,

在构造函数中,我从@ angular / core注入Injector实例

  constructor(
    private loader: NgModuleFactoryLoader,
    private injector: Injector
  ) {}

然后我使用create方法来创建新标签页或注入现有标签页,如下所示:

  private openInternal(newTab: OpenNewTabModel, moduleFactory?: NgModuleFactory<any>) {
    const newTabItem: TabItem = {
      label: newTab.label,
      iconName: newTab.iconName,
      component: {
        componentType: newTab.componentType,
        moduleFactory: moduleFactory,
        injector: newTab.data
          ? Injector.create(newTab.data, this.injector)
          : this.injector
      }
    };

我收到此警告:

{
    "resource": "/.../tab.service.ts",
    "owner": "typescript",
    "code": "1",
    "severity": 4,
    "message": "create is deprecated: from v5 use the new signature Injector.create(options) (deprecation)",
    "source": "tslint",
    "startLineNumber": 51,
    "startColumn": 22,
    "endLineNumber": 51,
    "endColumn": 28
}

Injector.create的新签名如何?

1 个答案:

答案 0 :(得分:0)

Injector 类有两个静态创建方法,使用具有选项签名的一个:

static create(options: {
    providers: StaticProvider[];
    parent?: Injector;
    name?: string;
}): Injector;

你也可以有一个额外的方法来返回注入器:

private openInternal(newTab: OpenNewTabModel, moduleFactory?: NgModuleFactory<any>) {
  const newTabItem: TabItem = {
    label: newTab.label,
    iconName: newTab.iconName,
    component: {
      componentType: newTab.componentType,
      moduleFactory: moduleFactory,
      injector: newTab.data ? this.createInjector(newTab.data) : this.injector,
    },
  };
}

private createInjector(tabData: any) {
  return Injector.create({
    providers: [{ provide: 'tabData', useValue: tabData }],
  });
}