角度customElements:当从DOM中删除customElements时,如何使服务自毁?

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

我有2个Angular项目。第一个将作为自定义Web元素构建的项目,供另一个项目使用。

[[Project 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 }));
        }
    }
}

[[Project B]-app.component.html:

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

但是,当我从DOM中删除自定义元素(使用ngIf或display:none时,MyService OnDestroy方法未调用,因为它是在Project A app.module中提供的。

  • [我尝试在AppComponent提供程序中提供MyService,它允许调用OnDestroy,但由于没有在根目录(app.module)中提供,因此我无法在Project A的CustomModules中使用相同的服务。

如何在从DOM中删除自定义元素时如何同时为MyServiceAppComponent提供CustomModules并确保MyService OnDestroy被调用?

angular custom-element
1个回答
0
投票

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

[Project B]-app.component.html

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

[Project A(自定义元素)]-app.component.ts

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

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

© www.soinside.com 2019 - 2024. All rights reserved.