One of my components subscribes to router events like so:
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event re-initalise the component
if (e instanceof NavigationEnd) {
let p = e as NavigationEnd;
console.log(p.urlAfterRedirects);
console.log("im being called from NavigationEnd");
this.ngOnInit();
}
});
}
I use this code to reload the component when the user navigates to the component a second time via a button. While debugging a problem i noticed that when i navigate to another component this piece of code still remains active even though the component that its part of is not. Can someone explain why and how this code stays active even though the component itself is no longer there? Shouldn't the code cause an error when it can no longer reach this.ngOnInit() ?
I can solve this problem by unsubscribing to it in the onDestroy method but i would really like to know how the code is able to stay active when the component is no longer there, and why this.ngOnInit() doesn't throw an error since the component is not active.