Ionic 4 - how to pass data between pages using navCtrl or Router service

Han Che picture Han Che · Sep 5, 2018 · Viewed 33.3k times · Source

In Ionic 3 you could use the second argument of the navController to pass data to the next page and retrieve it with the navParams service.

This was a really convenient feature. Is there an equivalent api for routing in Ionic 4?

You can always JSON.stringify the object/array to the routerParams, which in my opinion is less convenient.

In Ionic 4 you can pass data with the modalController using ComponentProps and @Input() making it more suitable of a quick push/pop implementation.

EDIT

My intention with this question is to find out if there are any native APIs from Angular 6+ or Ionic 4+. I am well aware of ways to implement a custom service or resolver to accomplish this.

The goal is to use ionic's and angular's api to its fullest, since in larger projects each custom code requires documentation and increases complexity.

Answer

Adam Thoor picture Adam Thoor · Sep 7, 2018

I have solved this by wrapping the Ionic NavController in a provider which has functions to set a value to a variable and a function to get it again. Similar to this.navParams.get('myItem').

Take a look at the following;

import { Injectable } from '@angular/core';
import { NavController } from '@ionic/angular';

@Injectable()
export class Nav {
    data: any;

    constructor(public navCtrl: NavController) {
        // ...
    }

    push(url: string, data: any = '') {
        this.data = data;

        this.navCtrl.navigateForward('/' + url);
    }

    pop(url) {
        this.navCtrl.navigateBack('/' + url);
    }

    get(key: string) {
        return this.data[key];
    }
}

Hope this helps!