6

I want to make a callback between two page. In the page 1, i have this code:

  DataInfo= [
    {
       Price: 0,
       ClosePrice: 0,
       UpdateTime:"",
       DefaultPrice:0
    }

  ] 

GetClosePrice(i):number{
return DataInfo[i].ClosePrice;
}

i want to get the value of 'i' from the page 2, How can i load the function GetClosePrice() when the navcontroller return to the page 1 (this.navCtrl.pop())

3 Answers 3

24

SOURCE PAGE CLASS

this.navCtrl.push(Page,
{
    data: this.data,
    callback: this.getData
});

getData = data =>
{
  return new Promise((resolve, reject) => {
    for (let order of orders) {
      this.data = data;
    }
    resolve();
  });
};

TARGET PAGE CLASS

constructor(public navCtrl: NavController, public navParams: NavParams)
{
  this.callback = this.navParams.get('callback');
  this.data = this.navParams.get('data') || [];
}

sendData(event: any): void
{
  this.callback(this.data).then( () => { this.navCtrl.pop() });
}

TARGET PAGE TEMPLATE

<button ion-button (click)="sendData($event)">
1
  • You need to be careful to declare the getData function exactly as here, i.e. with an arrow function (having no bindings to the 'this'). Declaring it as a method of the source page class did't work for me, as it was executed in the context of the target page class.
    – LoBo
    Commented Jan 24, 2019 at 16:41
10

I answered similar question in Ionic forum. I just used Events listeners to achieve this behaviour.

MainPage-

import { NavController, Events } from 'ionic-angular';
import { OtherPage } from '../other/other';

export class MainPage{
    constructor(private navCtrl: NavController,
                private events: Events) { }

    private pushOtherPage(){
        this.events.subscribe('custom-user-events', (paramsVar) => {
            // Do stuff with "paramsVar"

            this.events.unsubscribe('custom-user-events'); // unsubscribe this event
        })

        this.navCtrl.push(OtherPage); // Push your "OtherPage"
    }
}

OtherPage-

export class OtherPage {
    // Under some function
    this.navCtrl.pop().then(() => {
        // Trigger custom event and pass data to be send back
        this.events.publish('custom-user-events', myCustomParams);
    });
}
3
  • 1
    This is a much better solution than the accepted answer, especially if you want to do UI related callback in the pusher's view.
    – Henry Cho
    Commented Aug 25, 2018 at 11:07
  • 1
    Best of all solutions the I've found so far, to fetch data while popping the second page and returning to the previous page. Perfectly working!
    – vss
    Commented Sep 1, 2018 at 8:34
  • There is also a supplied callback function based approach. Commented Oct 15, 2019 at 10:51
0

Try this one - ionic2 pop with params

Not the answer you're looking for? Browse other questions tagged or ask your own question.