emulcahy
emulcahy

Reputation: 1065

Ionic framework 3 - detect 'back' event on previous page

I have a 'view item list' page and a 'view item details' page. From the 'view item list' page, I am using navCtrl.push('viewItemDetails'). On the item details page, the user may change something, and then hit 'back'.

What I want to do is refresh the 'view item list' page when the user comes back from the details page.

I have tried:

One option would probably be to use observables on the item list page, but I really would like to do this with lifecycle events if possible.

Any ideas?

Upvotes: 0

Views: 778

Answers (1)

Ariel
Ariel

Reputation: 1527

2 options:

  1. Use ModalController instead of NavController, then you know when the modal is dismissed: ModalController.

  2. Use Events in combination with ionViewDidLeave.

Detail page

import { Events } from 'ionic-angular';

constructor(
    private events: Events,
) {
}

ionViewDidLeave() {
    let data = { id: 123 };
    this.events.publish('list-page:refresh', data);
}

List page

You can subscribe to the event before doing the push. And unsubscribe after receiving the event data.

import { Events } from 'ionic-angular';

  constructor(
        private events: Events,
    ) { }

public goToDetail(yourData): void {
    this.events.subscribe('list-page:refresh', (data) => {
        this.yourRefreshMethod(data);
    });
    this.navCtrl.push('your-view', yourData);
}

public yourRefreshMethod(data): void {
    // your code to refresh the page.
    this.events.unsubscribe('list-page:refresh');
}

As you can see, before going to the detail page (with params if you wish), it will subscribe to the event for a refresh. When you go into the detail page, when it leaves, it fires the event with any data you want.

After leaving, the event is triggered in the "ListPage", which will call yourRefreshMethod with any data you send.

Upvotes: 3

Related Questions