Angular 12 - returns 循环

Angular 12 - returns loop

我正在从 api 获取数据作为对象。我正在尝试在 component.html 中使用 ngFor,但出现此错误

找不到 'test' 类型的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays.

所以我的对象是这样的:

{ID:9,姓名:'test',用户名:'testmg',电子邮件:'test@gmail.com',email_verified_at:空,...}

我该如何解决这个问题?

profile.component.ts

  username:any
  playerData:any

  constructor(private dataService: DataService,private router: ActivatedRoute) { }

  ngOnInit(): void {
    this.username = this.router.snapshot.params.username
    this.getOne()
  }


  getOne(){
    this.dataService.getProfile(this.username).subscribe(res=>{
      this.playerData = res
    })
  }

简介.component.html

 <div *ngFor="let item of playerData">
     {{item}}
 </div>

求解是什么意思?该消息不言自明:您有一个对象 playerData;而且你不能 *ngFor 对象!

如果你想遍历对象的属性你可以这样做:

<div *ngFor="let item of Object.Keys(playerData)">
   {{item}} : {{playerData[item]}}
</div>

举例

在将响应分配给 this.playerData 之前,使用 RxJs 映射将对象包装在数组中,模板中不需要更改。

this.dataService.getProfile(this.username).pipe(
 map(resp => [resp])
).subscribe(res=>{
  this.playerData = res;
}

部分代码优化:

声明playerData

playerData$: Observable<any[]>;

将 API 响应绑定到 playerData$

this.playerData$ = this.dataService.getProfile(this.username).pipe(
    map(resp => [resp])
);

在模板中使用 AsyncPipe 将为我们订阅和取消订阅:

<div *ngFor="let item of playerData$ | async">
    {{item}}
</div>

这样你就不需要订阅和取消订阅 Observable。

使用进口

import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';