我有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中提供的。
MyService
,它允许调用OnDestroy,但由于没有在根目录(app.module)中提供,因此我无法在Project A的CustomModules中使用相同的服务。如何在从DOM中删除自定义元素时如何同时为MyService
和AppComponent
提供CustomModules
并确保MyService OnDestroy被调用?
在您的项目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
因此,我希望服务实例与自定义组件并行销毁。