将对象作为路由中的参数返回[对象对象]

问题描述 投票:0回答:1

这在我的routing.module中:

{path: 'hero' component: HeroComponent}

这就是我通过路线传递对象的方式:

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

在我的英雄组件中,我读取了类似的对象:

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

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

[Object object]

并读取对象的属性,例如.id返回:

undefined

如果尝试使用*ngFor进行迭代,则会得到:

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

为什么会这样?

angular typescript angular-routing angular-router
1个回答
0
投票

尝试使用JSON.stringify()发送字符串

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

并将其解析回接收方

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

并且如果Obj变量是一个对象,则需要使用keyvalue管道使用*ngFor指令对其进行迭代

<ng-container *ngFor="let item of Obj | keyvalue">
  {{ item.key }}: {{ item.value }}
</ng-container>
© www.soinside.com 2019 - 2024. All rights reserved.