角形自定义元素不会破坏服务

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

我怎么知道何时从DOM中删除自定义组件。这样我就可以销毁服务(在服务中使用OnDestroy生命周期)。这些服务被注入到根模块。

观察到当从DOM中删除自定义组件时,服务不会被破坏。

创建自定义元素:

ngDoBootstrap(appRef: ApplicationRef, platformRef: PlatformRef) {
        if (environment.build=== 'custom') {
            if (!customElements.get('custom-component')) {
                customElements.define('custom-component', createCustomElement(AppComponent, { injector: this.injector }));
        }
}

服务已注入AppModule(根):

@Injectable({
  providedIn: 'root',
})
  • 从DOM中删除自定义组件时
  • AppComponent OnDestroy生命周期被触发
  • Services OnDestroy生命周期不会被触发<====期望被调用

目前,我在AppComponent OnDestroy()方法中有一个讨厌的解决方法,该方法手动调用了我所有的Services OnDestroy()方法。但是我有30项服务,这是否意味着我需要重复30次类似的代码?

AppComponent-OnDestroy()

ngOnDestroy() {
   this.serviceA.ngOnDestroy();
   this.serviceB.ngOnDestroy();
   this.serviceC.ngOnDestroy();
   ...
   ...
}
angular web-component custom-element
1个回答
0
投票

[ngDestroy可用于Angular.io的Angular Service

    @Injectable()
    export class MyService {
     constructor(parent: OtherInjectedService) {
       console.log('Service created..');
     }

     ngOnDestroy() {
       console.log('Service destroyed...');
     }
    }

但是您可以使用RxJS takeUntil退订。代码是通用代码,因此您需要基于代码来实现。感谢文章here

class MyGenericComponent extends SomeFrameworkComponent {
 updateData(data) {
  // do something framework-specific to update your component here.
 }

 onMount() {
   const data$ = this.getData();
   const cancelBtn = this.element.querySelector(‘.cancel-button’);
   const rangeSelector = this.element.querySelector(‘.rangeSelector’);
   const cancel$ = Observable.fromEvent(cancelBtn, 'click');
   const range$ = Observable.fromEvent(rangeSelector, 'change').map(e => e.target.value);

   const stop$ = Observable.merge(cancel$, range$.filter(x => x > 500))
   this.subscription = data$.takeUntil(stop$).subscribe(data => this.updateData(data));
 }

 onUnmount() {
  this.subscription.unsubscribe();
 }
© www.soinside.com 2019 - 2024. All rights reserved.