angular - ngFor 循环内的函数无限调用
问题描述
function 此函数返回每个订单的用户名。
我在我的 component.html 中调用这个函数,每个订单 ngFor 循环运行的地方。ngFor 循环 this 不断循环并无限调用 api。我真的很乐意提出任何建议。谢谢你。
解决方案
这里有多个问题。
- 请不要将代码作为图像发布。
- 您现在期望人们输入您的代码来复制问题。
- 如果外部图像主机出现故障,您的问题将变得毫无用处。
- 您不能从订阅中返回任何内容。您正在将回调传递给
subscribe()
函数,它们不能返回任何内容。 - 在模板插值
{{ }}
或数据绑定中调用带有[]=()
默认更改检测策略的函数将触发每个更改检测周期的函数,因此“无限”调用。
您要么需要获取控制器 (*.ts) 中的所有信息,要么async
在模板中使用管道。
- 使用
forkJoin
withArray#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>
推荐阅读
- networking - 有没有办法为 Kubernetes 中的传出流量保留源端口?
- bitbucket - Bitbucket API:在 webhook 有效负载中获取工作区对象
- javascript - 发出错误报告命令,但不断收到“类型错误:client.fetchUser 不是函数” Discord.js
- python - 将 json.loads 应用于具有 dask 的数据框列
- css - CSS - 将鼠标悬停在具有较小文本的链接上时,导航容器会拉伸
- java - .StaleElementReferenceException 即使添加了断言
- amazon-web-services - 镜像推送到 ECR 时如何部署到 ECS?
- c++ - C++多态模板类,模板类型对象的实例化
- c# - 在 C# 中获取第一个图像结果的 url
- java - 使用 gradle 6.3、OpenJDK 14 和 OpenJFX 14 部署 JavaFX 应用程序