Search code examples
angulartypescriptangular-routingangular-router

Passing object as parameter in route returns [Object object]


This is in my routing.module:

{path: 'hero' component: HeroComponent}

And this is how I pass the object though route:

this.router.createUrlTree(['/hero', {my_object: this.Obj}]));
window.open(url, '_blank');

In my hero component I read object like:

this.route.snapshot.paramMap.get('my_object');

console.log(this.route.snapshot.paramMap.get('my_object');) returns:

[Object object]

and reading a property of object for example .id returns:

undefined

If I try to iterate it with *ngFor I get:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

Why is this happening?


Solution

  • Try to send a string using JSON.stringify()

    this.router.createUrlTree(['/hero', {my_object: JSON.stringify(this.Obj)}]));
    

    and parse it back it in the recipient

    this.Obj = JSON.parse(this.route.snapshot.paramMap.get('my_object'));
    

    And if the Obj variable is an object, you need to use keyvalue pipe to iterate over it using *ngFor directive

    <ng-container *ngFor="let item of Obj | keyvalue">
      {{ item.key }}: {{ item.value }}
    </ng-container>