【问题标题】:Angular | Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays角度 |找不到类型为“对象”的不同支持对象“[对象对象]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2023-01-26 21:21:30
【问题描述】:

我在使用 Angular 时遇到问题,我正在尝试使用 *ngFor 从我的 json 中获取数据,但出现此错误:

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

我该如何解决呢?下面是我的代码。

我的服务.ts

  getChannels(): Observable<Channel[]> {
    const url = this.urlGet;
    return this.http.get<Channel[]>(url)
  }

我的组件.ts

channels: Channel [] = [];

constructor(private channelService: ChannelService) { }

  ngOnInit() {
    this.getChannel();
  }
 getChannel() {
    this.channelService.getChannels().subscribe(response => this.channels = response)
  }

来自 api 的 json

{
  "result": 
  [
    {
      "id": 1,
      "name": "Channel 1"
    },
    {
      "id": 2,
      "name": "Channel 2"
    },
    {
      "id": 3,
      "name": "Channel 3"
    }
  ]
}

我的组件.html

<div *ngFor="let channel of channels">
   {{channel.name}}
 </div>

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的 getChannels 函数应如下所示:

    getChannel() {
        this.channelService.getChannels().subscribe(response => this.channels = response.result)
      }
    

    您正在分配整个对象而不是内部数组。

    将来您应该使用正确的类型作为 http 调用函数的返回值:

      getChannels(): Observable<{result:Channel[]}> {
        const url = this.urlGet;
        return this.http.get<{result:Channel[]}>(url)
      }
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2019-01-31
      • 2022-11-18
      • 2022-11-19
      • 2018-07-14
      相关资源
      最近更新 更多