Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 Angular 7 - passing object/data to another page [duplicate]

I would like to pass a JSON object to another page. What I've tried is to pass the JSON string using Angular router ActivatedRoute like this:

this.router.navigate(['details', details]);

and then retrieve it like this:

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


constructor(private activatedRoute: ActivatedRoute) { 
  }


ngOnInit() {

  this.activatedRoute.params.subscribe(extras => {
     console.log(extras);
     this.JSONObject = extras;
  });

}

It is possible to do it this way but what happened was the nested JSON objects becomes inaccessible. It turns into this string:

"[object Object]"

The stringified JSON object is fine and accessible before I pass it. Another problem is that it appends the JSON string to the url so it doesn't look that nice. From what I read as well, it is not a good practice to pass something more than just an id this way.

I am thinking of something like passing objects as intent extras between activities in Android. I've searched the documentations, forums, and previous stackoverflow questions but I didn't found any solution that enables me to achieve this. Is there any other way of passing objects between pages using Angular router in Ionic4?

like image 703
tyn Avatar asked Jan 22 '19 08:01

tyn


People also ask

How do I pass data from one page to another page in ionic 4?

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

How do you use NavParams in ionic 4?

Ionic 4 doesn't have a universal NavParams object anymore. Navigation is based on Angular routing. Hence the preferred way for passing parameters to a page are route parameters. Since this makes them a part of the URL, they can't be structured objects anymore.


1 Answers

I solved it using a service with a simple setter and getter just like in this question that I later found:

Ionic 4. Alternative to NavParams

First, I create a service with setter & getter:

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

@Injectable({
  providedIn: 'root'
})
export class NavExtrasService {

    extras: any;

      constructor() { }

      public setExtras(data){
        this.extras = data;
      }

      public getExtras(){
        return this.extras;
      }
    }

Let's say I'm navigating from page A to page B, in page A:

this.navExtras.setExtras(extras)
this.router.navigateByUrl('page-b');

Then in Page B, I retrieve the extras this way:

this.location = navExtras.getExtras();

It works so far although I'm still not sure if there are better ways to do it..

like image 164
tyn Avatar answered Oct 03 '22 01:10

tyn