在路由中将对象作为参数传递返回 [Object object]

che*_*ire 2 typescript angular-routing angular angular-router

这是在我的 routing.module 中:

{path: 'hero' component: HeroComponent}
Run Code Online (Sandbox Code Playgroud)

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

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

在我的英雄组件中,我读取对象如下:

this.route.snapshot.paramMap.get('my_object');
Run Code Online (Sandbox Code Playgroud)

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

[Object object]
Run Code Online (Sandbox Code Playgroud)

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

undefined
Run Code Online (Sandbox Code Playgroud)

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

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Mic*_*l D 6

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

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

并将其解析回收件人

this.Obj = JSON.parse(this.route.snapshot.paramMap.get('my_object'));
Run Code Online (Sandbox Code Playgroud)

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

<ng-container *ngFor="let item of Obj | keyvalue">
  {{ item.key }}: {{ item.value }}
</ng-container>
Run Code Online (Sandbox Code Playgroud)