Unsubscribe from Navigation Events

Posted: 12/13/2017 8:39 AM

I recently ran into a problem where an Angular Component was still responding to Navigation Events even after having navigated away from that route.

When subscribing to an Observable, be sure to store the subscription in a global variable and call the .unsubscribe() function when the component is being destroyed.

export class MyComponent implements OnInit, OnDestroy {

    constructor (private router: Router) { }

    // stores the subscription object
    navSubscription: Subscription = null;

    // called when the component is initialized
    ngOnInit() {
        this.navSubscription = this.router.events.subscribe((event: any) => {
            // test if the event is an end navigation
            if (event instanceof NavigationEnd) {
                // do something here
            }
        });
    }

    // called when the component is destroyed
    ngOnDestroy() {
        this.navSubscription.unsubscribe();
    }
}