如果我们有一个动态(不是声明式动态创建)的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
答案 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()
})