2

I was wondering if it is possible to give navParams with the poptoRoot function. What they discuss Here is not working for me. Is there any workaround? To share data between the poptoRoot page and the current page?

4

1 Answer 1

3

I'm afraid that popToRoot only accepts a parameter of the NavOptions type (related to the transition of the page), so you would need to send the data back to the root page:

Using Events.

You could subscribe to that event on the root page, and then publish the event in the child page, sending the data as part of that event.

import { Events } from 'ionic-angular';

// Child page: publish the event sending the data
constructor(public events: Events) {}

someMethod(data) {
  this.events.publish('data:modified', data);
}


// Root page: subscribe to the event to get the data
constructor(public events: Events) {
  events.subscribe('data:modified', (data) => {
    // Handle the data...
  });
}

Using a shared service

If the parameter you need to send is something simple as a number or an array, you could use the shared service to store that data there, so the root page can read it from the service, and the child page can modify it from there as well.

If you need to execute some logic every time the data changes, then you could use a Subject like this:

@Injectable()
export class YourItemsService {

    public onItemsChange: Subject<any> = new Subject<any>();

    // ...

    public changeItems(someParam: any): void {
        // ...

        // Send the new data to the subscribers
        this.onItemsChange.next(newItems);
    }

}

That way the child page can use the service to change the data, knowing that the change will also be propagated to all the pages that are subscribed to it:

@Component({
    selector: 'child-page',
    templateUrl: 'child-page.html'
})
export class ChildPage {

    constructor(private yourItemsService: YourItemsService) {}

    updateItems(data: any) { 
        // Use the service to modify the data, keeping everyone updated
        this.yourItemsService.changeItems(data);
    }

}

And the root page could subscribe to changes on the data, to execute some logic every time it changes:

@Component({
    selector: 'root-page',
    templateUrl: 'root-page.html'
})
export class RootPage {

    private itemsChangeSubscription: Subscription;

    constructor(private yourItemsService: YourItemsService) {
        // Subscribe to changes in the items
        this.itemsChangeSubscription = this.yourItemsService.onItemsChange.subscribe(data => {
            // Update the data of the page...
            // ...
        });
    }

    ionViewWillUnload() {
        // Clear the itemsChangeSubscription
        this.itemsChangeSubscription && this.itemsChangeSubscription.unsubscribe();
    }
}

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