ComponentRef.destroy()方法是否也取消订阅组件事件发射器?

时间:2019-01-11 04:34:54

标签: javascript angular typescript rxjs

如果我们有一个动态(不是声明式动态创建)的ComponentRef实例,并且在该实例上调用destroy(),将取消订阅已订阅的EventEmitter实例的任何订阅

例如,如果我们有一个output EventEmitter且我们这样订阅:

this.componentRef.instance.output.subscribe(event => console.log(event));

我们打电话给componentRef.destroy()来取消订阅output EventEmitter的事情吗?

总结答案的文章

https://medium.com/@ole.ersoy/subscribing-to-dynamic-component-eventemitters-4f931a5013e3

https://medium.com/@ole.ersoy/cleaning-up-subscriptions-to-dynamic-component-event-emitters-ad08c838c7a8

2 个答案:

答案 0 :(得分:1)

调用subscribe方法时,将返回一个预订对象。如果我跟踪那个对象。每当Angular破坏组件时,您都必须调用unsubscribe。

E.x:

ngOnDestroy() {
   this.sub.unsubscribe();
}

它不会退订ngOnDestroy()

答案 1 :(得分:1)

componentRef有一个onDestroy回调,您可以挂钩以清理订阅

  /**
   * A lifecycle hook that provides additional developer-defined cleanup
   * functionality for the component.
   * @param callback A handler function that cleans up developer-defined data
   * associated with this component. Called when the `destroy()` method is invoked.
   */
  abstract onDestroy(callback: Function): void;
  

示例

const sub=this.componentRef.instance.output.subscribe(event => console.log(event));
this.componentRef.onDestroy(()=>{
    sub.unsubscribe()
})