Search code examples
angularangular4-router

Autosave the form/model content on route change in angular 4


In angular 4 application, I am moving from one module to other I want to save my content automatically so I need to identify the change in route.

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

I have used this code but this call is incrementing for every visit. Its similar to Gmail compose how it saves data to draft when I moved from composing screen to other.


Solution

  • You are leaving the subscription open when leaving, so it will increment. You need to unsubscribe:

    import { Subscription } from 'rxjs/Subscription';
    
    // ...
    
    sub = new Subscription();
    
    // ...
    
    this.sub = router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    
    });
    
    // ...
    
    ngOnDestroy() {
      this.sub.unsubscribe();
    }