首页 > 解决方案 > ngFor 循环内的函数无限调用

问题描述

function 此函数返回每个订单的用户名。

我在我的 component.html 中调用这个函数,每个订单 ngFor 循环运行的地方。ngFor 循环 this 不断循环并无限调用 api。我真的很乐意提出任何建议。谢谢你。

标签: angular

解决方案


这里有多个问题。

  • 请不要将代码作为图像发布。
    • 您现在期望人们输入您的代码来复制问题。
    • 如果外部图像主机出现故障,您的问题将变得毫无用处。
  • 您不能从订阅中返回任何内容。您正在将回调传递给subscribe()函数,它们不能返回任何内容。
  • 在模板插值{{ }}或数据绑定中调用带有[]=()默认更改检测策略的函数将触发每个更改检测周期的函数,因此“无限”调用。

您要么需要获取控制器 (*.ts) 中的所有信息,要么async在模板中使用管道。

  • 使用forkJoinwithArray#map并行获取所有订单的数据。

控制器 (*.ts)

ngOnInit() { // <-- or wherever the `dataArray` is initialized
  forkJoin(
    this.dataArray.map(order => 
      getuserdata(order.user_id).pipe(
        map(data => ({
          ...order,
          data: data
        }))
      )
    )
  ).subscribe({
    next: (array: any) => this.dataArray = array,
    error: (error: any) => { /* handle error */ }
  });
}

getuserdata(userid) {
  const userId = { params: { id: userid }};
  return this._order.getUserdata(userId).pipe(
    map(res => {
      this.userData = res;
      return res.userdata.fullname
    })
  );
}

模板 (*.html)

<td>{{ order.data }}</td>

推荐阅读