I am wondering If I subscribe to stream in my constructor like this:
_eventEmitterService.event.subscribe((msg)=>{})
So when I change the view to different component, and come back, the events are triggered twice from that stream. Do I need to unsubscribe each time I change the component, by using ngOnDestroy
?
Thanks
I found it! And yes, per documentation as stated in the angular2 lifecycle-hook
guide:
ngOnDestroy
Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.
So yes, you need to unsubscribe from observables on ngOnDestroy()
Just an additional hint to the Pierre's great answer. The async
pipe automatically unsubscribes observables it's applied on. So you need to unsubscribe for observables you manage by your own.
See this line in source code:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With