[英]Does a ComponentRef.destroy() method also unsubscribe the Components Event Emitters?
If we have a dynamic (Created dynamically - not declaratively) ComponentRef
instance, and we call destroy()
on the instance, will that unsubcribe any subscriptions to EventEmitter
instances that are subscribed to. 如果我们有一个动态的(动态创建的-不是声明性创建的)
ComponentRef
实例,并且在该实例上调用destroy()
,将取消订阅已订阅的EventEmitter
实例的任何订阅。
For example if we an output
EventEmitter
and we subscribe to it like this: 例如,如果我们
output
EventEmitter
并按如下方式订阅它:
this.componentRef.instance.output.subscribe(event => console.log(event));
And we call componentRef.destroy()
will that take care of unsubscribing the subscription to the output
EventEmitter
? 我们将调用
componentRef.destroy()
来取消订阅output
EventEmitter
的订阅吗?
https://medium.com/@ole.ersoy/subscribing-to-dynamic-component-eventemitters-4f931a5013e3 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 https://medium.com/@ole.ersoy/cleaning-up-subscriptions-to-dynamic-component-event-emitters-ad08c838c7a8
When subscribe method is called there is a subscription object returned. 调用subscription方法时,将返回一个预订对象。 If I keep track of that object.
如果我跟踪那个对象。 You have to can call unsubscribe whenever Angular is destroying the component.
每当Angular销毁组件时,您都必须调用unsubscribe。
Ex: 例如:
ngOnDestroy() {
this.sub.unsubscribe();
}
It will not unsubscribe from ngOnDestroy()
不会取消订阅
ngOnDestroy()
There's a onDestroy
callback from componentRef that you can hook to clean up the subscriptions 有一个来自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;
example
例
const sub=this.componentRef.instance.output.subscribe(event => console.log(event));
this.componentRef.onDestroy(()=>{
sub.unsubscribe()
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.