1

我有一个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什么?

4

2 回答 2

2

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

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 }],
  });
}
于 2021-02-17T13:33:48.753 回答
0

Injector.create 方法有一个重载版本,其中一个参数是选项,并且要修复该警告,请声明一个包含您的注入器配置的 const,然后将其传递给 Injector.create() 方法。

    const options = {
      providers: newTab.data,
      parent: this.injector
    };
    Injector.create(options);
于 2021-12-08T03:40:30.637 回答