How to get object in queryparams using Typescript?

Maniraj Murugan picture Maniraj Murugan · Sep 10, 2018 · Viewed 11.1k times · Source

In a button click i have function as,

  inviewMockupEvent(data) {
    console.log(data);
    this.router.navigate(['/page-mockup'], { queryParams: { data: data },  skipLocationChange: true });
  }
console.log(data) give the result as {mockup_id: "123", project_id: "456", module_id: "678", release_id: "890", requirement_id: "432", …}

In navigated component i am getting the data as follows,

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(params => {
      let data = params['data'];
      console.log(data);
      console.log(JSON.stringify(data));
    });

Where,

console.log(data) gives output as [object Object]
console.log(JSON.stringify(data)) gives output as "[object Object]"

And also,

console.log(data.mockup_id) gives result undefined

Here i need to retrieve the object values, but unable to get it. Kindly help me to retrieve the data through query params and fetch using typescript ngOnit without using html.

Answer

user4676340 picture user4676340 · Sep 10, 2018
  1. You're adding an useless layer to your object. Spread it.

    this.router.navigate(['/page-mockup'], { queryParams: { ...data },  skipLocationChange: true });
    
  2. If you want to use the array notation, then use the array variable, not the map variable.

  3. Display the correct variables.

    this.activatedRoute.queryParams.subscribe(params => {
      let data = params;
      console.log(data.mockup_id);
    });
    

Stackblitz