Angular2:动态创建的注入器(通过 Injector.create(...) 创建)是否被销毁?

问题描述 投票:0回答:1

需要对使用

Injector.create
方法创建的注入器的生命周期进行一些评论

我尝试通过

ViewContainerRef.createComponent(...)
创建一个组件,并使用传入参数的自定义注入器提供动态生成的依赖项。该注入器有一个从主机组件继承的父注入器。

一段时间后,当我销毁该组件时,我注意到我在动态注入器中提供的服务没有执行

ngOnDestroy
方法。

尽管如此,通过

@Component
装饰器(在父组件中)提供的所有服务都已成功销毁(事实上,它们总是以这种方式销毁)。

这种行为的原因可能是什么?有没有办法销毁动态创建的注入器?

这是一个 StackBlitz 示例: https://stackblitz.com/edit/stackblitz-starters-vstiqn

当我通过切换按钮关闭父组件时,我希望

ChildService
会像
ngOnDestroy
那样调用
ParentService
方法。

angular dependency-injection dynamically-generated application-lifecycle angular-injector
1个回答
0
投票

手动销毁

Injector
的最佳方法是使用具有
EnvironmentInjector
方法的
destroy

以你的例子来说:

export class ParentComponent implements OnInit, OnDestroy {
  myInjector?:EnvironmentInjector

  constructor(
    private readonly viewContainerRef: ViewContainerRef,
    private readonly environmentInjector: EnvironmentInjector,
    private readonly parentService: ParentService
  ) {}

  ngOnInit() {
    this.myInjector = createEnvironmentInjector( [ChildService],
      this.environmentInjector,
    ); // create

    this.viewContainerRef.createComponent(ChildComponent, {
      injector: this.myInjector,
    });
  }

  ngOnDestroy() {
    this.myInjector?.destroy() // destroy
    console.log('ParentComponent destroyed'); 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.