Angular customElements:当从DOM中删除customElement时,如何让服务自行销毁



我有两个Angular项目。第一个项目,它将被构建为另一个项目使用的自定义web元素。

[项目A]-app.module:

@NgModule({
declarations: [
AppComponent,
],
imports: [
CustomModules
]
providers: [
MyService  <---- this did not get destroyed when <custom-element> was removed from DOM
...
]
})
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap(appRef: ApplicationRef) {
if (environment.mode=== 'production') {
customElements.define('custom-element', createCustomElement(AppComponent, { injector: this.injector }));
}
}
}

[项目B]-app.component.html:

包含<*ngIf="..." custom-element></custom-element>以显示整个项目A。

然而,当我从DOM中删除自定义元素时(使用ngIf或display:none(,MyServiceOnDestroy方法没有被调用,因为它是在Project A app.module中提供的。

  • 我尝试在AppComponent提供程序中提供MyService,这允许调用OnDestroy,但我无法在项目A中的CustomModules中使用相同的服务,因为它不是在root(app.module(中提供的

如何向AppComponentCustomModules提供MyService,并确保从DOM中删除自定义元素时调用MyService OnDestroy?

在您的项目B中,使用Injector类创建MyService的实例,然后将该实例绑定到您的自定义元素中作为输入:

[项目B]-app.component.html

myServiceInstance : any
constructor (..., this.injector: Injector) {
...
this.myServiceInstance = this.injector.get(MyService)
}

[项目A(自定义元素(]-应用程序组件.ts

...
@Input() serviceInstance: any;
...
// user serviceInstance like you use your normal service

这样,我希望服务实例与自定义组件并行销毁。

相关内容

最新更新