0
votes

I have an Ionic v4 page that configures a number of parameters for my application and I want to stuff all those values into an injected service right before I navigate off of the page so they can be used elsewhere in the application. I am using the Ionic Tabs Control / Page for navigation.

What is the best way to trap an event right before navigating off of the current page?

I have played with @angular/router NavigationStart events but once wired up it fires on all page transitions and I can't tell when I am leaving the desired config page. Or should I be using the old Ionic v3 NavControl?

Or should I just be updating my config service on all changes and not worry about leaving the page?

2
Have you tried doing this in the onDestroy lifecycle hook? I think that might just work because the page component might be destroyed when you leave it. - nipuna777
Ionic does not "destroy" pages when navigating away from a "page". ngOnDestroy is not called. - andleer

2 Answers

1
votes

I would delete my original question if I could but I can't. These issues were all with Beta 16 and now that I have upgraded to RC0, the issue has been resolved. Looks like all I was doing was correct but obviously there were nav related bugs.

0
votes

You can use ngOnDestroy life cycle hook which will be trigged when user leaves the View i.e component will be destroyed.

**Service:**

clearData(){
  //write logic to clear data
}

**Component:**

@Component({..})
export class MyComponent implements onDestroy{

ngOnDestroy(){
  this.service.clearData();
} 

For Ionic 4, by default ngOnDestroy won't be trigged when we navigate to another view. you can use ionViewWillLeave/ionViewDidLeave to handle observable unsubscription.

By using this.nav.navigateRoot(['/dashboard']); component will be destroyed and ngOnDestroy will be trigged.