Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Soumya B. Athani Avatar asked Dec 06 '25 02:12

Soumya B. Athani


1 Answers

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();
}
like image 109
AT82 Avatar answered Dec 09 '25 20:12

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!