How to go back multiple pages in ionic?

Hi, I have the page flow like below:
A->B->C->D
Somehow I will do a function in page"D", after it need to go back page"B".
How can I achieve that?
Using .pop() just can go back one page.
Using .push(B) is also not the solution, because the flow will become:
A->B->C->D->B
The solution I want is:
A->B
Anyone know how to achieve it? Thanks a lot.

You can use NavController’s getByIndex(index) method to go back to the view you want, if I’m not mistaking.
I haven’t personally give it a try but it seems to do just the same. Check it out in the documentation: https://ionicframework.com/docs/api/navigation/NavController/

Hope it helps you :slight_smile:

Alternative Solution

What you can do is using Events publish() just before calling pop() in a dismiss function, and then calling the Events subscribe() method in every previous pages’ constructor.

For example:

DismissFunction() {
  
  this.events.publish('go-back-to-B', some_value_here);
  this.navCtrl.pop();

}

Then in previous page (let say going from D to C):

Constructor() {
 
   this.events.subscribe('go-back-to-B', (some_value_here) => {
        //Now you can use this some_value_here to go back to B page using some if/else condition
        if(some_value_here ===  value_to_back_to_B_page) {
             // Call an event here to go to A
            this.Events.publish('go-back-to-A', some_value_here); 
            this.navCtrl.pop(); // goes back to B
        }      
   }); 
 
}

Then once in B page, finally do:

Constructor() {

     this.Events.subscribe('go-back-to-A', (some_value_here) => {
          if(some_value_here) {
              this.navCtrl.pop();  // goes back to A    
          }

     });

}

In this way you can pop the previous page before it loads on screen and go back multiple pages.

Remember to import Events and declaring it in constructor in each page:

import { Events } from 'ionic-angular';
constructor(public events: Events) { ... }

If you need a specific order you could also try to set the stack of pages using setPages() with an array of [A, B]

Thanks, I want to use indexOf for getting the page index, but it always return -1, do you know why?

this.navCtrl.popTo(this.navCtrl.getByIndex(this.navCtrl.inde‌​xOf(B)));

Change it slightly.

this.navCtrl.popTo(this.navCtrl.getByIndex(this.navCtrl.length() - 3));

1 Like