Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IONIC 4 - Angular Routing Parameters

I am busy with an upgrade of an old IONIC app to IONIC 4 and things are going well, however I am not able to find anything that details how to pass data and use pages in the routing of Angular.

Here is a code snippet of the problem:

OLD CODE

this.navCtrl.setRoot(VendorBookingDashboardProgressPage, { booking: temp });

In the above code, you will see that booking: temp is passed as a parameter for additional data and VendorBookingDashboardProgressPage is the reference page to navigate to.

NEW CODE

this.navCtrl.navigateRoot('vendor/vendor-booking-dashboard-progress'); -- This is where the booking: temp parameter is missing and must be included as well as hard-coded URL where page reference should rather be included but a string parameter is required.

I can live with hard-coding the URL, but the parameters are key and need to know how this can be achieved please.

like image 633
Edward Whitehead Avatar asked Dec 03 '22 09:12

Edward Whitehead


2 Answers

Try doing it using navigation extras like this:

import { NavigationExtras } from '@angular/router';
import { NavController } from '@ionic/angular';

constructor( public navCtrl: NavController) {
}

//this should be within a function
const navigationExtras: NavigationExtras = {
      queryParams: {
        special: JSON.stringify(temp)
      }
};
this.navCtrl.navigateRoot(['vendor/vendor-booking-dashboard-progress'], 
navigationExtras);

Then to retrieve it from the page routed to, try this within the page's ts file:

import { ActivatedRoute, Router } from '@angular/router';

data: any;

constructor(
  public activatedRoute: ActivatedRoute,
  private router: Router) {
}

ngOnInit(){
  this.activatedRoute.queryParams.subscribe(params => {
  if (params && params.special) {
    //store the temp in data
    this.data = JSON.parse(params.special);
  }
}
}
like image 63
Praise Hart Avatar answered Dec 19 '22 01:12

Praise Hart


You can try below method to pass data between pages

  1. Using Query Params
   let navigationExtras: NavigationExtras = {
      queryParams: {
        special: JSON.stringify(this.user)
      }
    };
    this.router.navigate(['details'], navigationExtras);
  1. Service and Resolve Function (legit)
  setData(id, data) {
    this.data[id] = data;
  }

  getData(id) {
    return this.data[id];
  }
  1. Using Extras State (new since Angular 7.2)
    let navigationExtras: NavigationExtras = {
      state: {
        user: this.user
      }
    };
    this.router.navigate(['details'], navigationExtras);

Ref : https://ionicacademy.com/pass-data-angular-router-ionic-4/

like image 33
Praveen Patel Avatar answered Dec 19 '22 00:12

Praveen Patel