Ionic 4: NavParams alternative


#1

In the Ionic 4, Ionic has removed the NavController and NavParams. So we can’t directly pass the JSON object between 2 pages.

So what can be the best way to send JSON object between 2 pages.

  • One option is using services, but for every page, we need to create a custom set and get method for data passing.

So what is the best way to pass dynamic JSON object between different pages in Ionic 4 with the help of angular routing?


#2

Yes, you would use services. In general, you would do something like pass an id through the URL, which can be read by the activated route, and then you would use that id to look up the data you want in a service.


#3

NavController is still available in Ionic 4 but the signatures have changed (i.e push/pop is no longer there).

However, I normally use a singleton service as communication bus between pages which I found to be far more powerful than navParams (i.e I don’t need to pass similar context around various pages, i just need to set it once etc… ).


#4

Providers for navigation
NavParams for modals


#5

I am using ionic 4. It does not accept to receive data using navparams.
Here is my sender page method:

  gotoFinalView(intent) {
    this.route.navigateByUrl(`${intent}`, this.destination);
  }

Receiver page line;

this.item = navParams.data;

What is the right approach to doing this in ionic 4. I am also uncertain about the validity of the method I have created in the sender page.


#6

This is how I solved my problem:
I created a Service with a setter and getter methods as;

import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class MasterDetailService {
  private destn: any;
  constructor() {}

  public setDestn(destn) {
    this.destn = destn;
  }

  getDestn() {
    return this.destn;
  }
}

Injected the Service and NavController in the first page and used it as;

  gotoFinalView(destn) {
    this.masterDetailService.setDestn(destn);
    this.navCtrl.navigateForward("destn-page");
  }

Extracted the data at the final page by;

constructor(
    private masterDetailService: MasterDetailService
  ) {
    this.destination = this.masterDetailService.getDestn();
  }