0
votes

I came across an issue in my android app which i have developed using ionic 4. My scenario is if i navigate through pages and came back using toolbar back button and again navigate to another pages and came back using android hardware back button then the pages i navigated back using toolbar back button shows in middle while using hardware back button.

Page A->B->C and then on toolbar back button C->B->A

Again page navigate A->D->E and then using hardware back button page navigate E->D->B->C->B->A

Unable to maintain state.

My Code

In app.component.ts constructor

this.router.events.subscribe(event => {
      const url = this.router.url //current url
      if (event instanceof NavigationEnd) {
        const isCurrentUrlSaved = this.navLinksArray.find((item) => { return item === url });
        if (!isCurrentUrlSaved) this.navLinksArray.push(url);
      }
    }); 


ngAfterViewInit() {

    this.backButtonSubscription = this.platform.backButton.subscribe(() => {
          if (this.router.url === '/tabs/home') {
            navigator['app'].exitApp();
          } else {
            if (this.navLinksArray.length > 1) {
              this.navLinksArray.pop();
              const index = this.navLinksArray.length - 1;
              const url = this.navLinksArray[index];
              this.navCtrl.navigateBack(url);
            }
          }
        });
      }
}

Thanks in advance.

1
Does both the hardware back button and toolbar back button use the same navLinksArray? Have you checked the navLinksArray to see if any additional pages are pushed into the array as it seems this is where the problem is? - Bart
@Bart please check my edited question. I am unable to get solution for this - santy

1 Answers

0
votes

I think, this.navCtrl.navigateBack(url); is pushing pages again like behavior is asynchronous just assuming.

Why dont you just pop the navigated page, lets say you have a generic function

ngAfterViewInit() {
 static BackButton(platform:Platform,navCtrl:NavController){
    platform.registerBackButtonAction(() => {
     navCtrl.pop();
   }, 0)
  }
}

and from the navigated page component just call, which must have constructor(public navCtrl: NavController,public platform:Platform){}, defined and then call generic method BackButton(this.platform,this.navCtrl) in same navigated page component.