javascript - 如何在 Angular 11 的 setInterval 延迟中使用 JSON 变量
问题描述
我正在从事 Angular 11 项目。我想在 JSON.data 中提到的“X”持续时间之后循环代码。这是我的以下代码片段。
数据.json
pageOrder: {
pageDetails:[
{
"duration": 5
},
{
"duration": 7
}]
}
app.component.ts
id: any = 0;
reloadFunction();
....
....
....
reloadFunction(): void {
// most of your code
console.log('wassup'); //**this should run after "duration", unfortunately its not working**
setTimeout(this.reloadFunction, pageOrder[this.id].duration * 1000);
this.id += 1;
if (this.id === pageOrder.length) {
console.log('wassup1', this.id);
this.id = 0;
}
}
不幸的是,代码只循环了一次,为什么???
解决方案
setTimeout
在不同的范围内调用函数。this
不指向对象。你需要绑定对象
setTimeout(this.reloadFunction.bind(this), pageOrder[this.id].duration * 1000);
推荐阅读
- javascript - 来自 iPad 魔术键盘的手势事件
- android - 如何获得使用范围存储的 Android 11 中的 File 对象编辑文件的权限?
- python - 有没有办法用熊猫只提取一列csv文件?
- c++ - OpenSSL 链接创建非常大的 exec 文件大小
- mongodb - 具有嵌套数组的 MongoDB 映射过滤器未按预期工作
- python - 通过传递 vars 在 python 中生成 bash 脚本
- amazon-web-services - http2 请求在 AWS 上通过 route53 连接的云端不起作用
- amazon-web-services - 双重代理请求 - 获取原始 IP
- python - 使用 python 自动化 Google Meet
- c++ - QPixmap - 当尺寸大于源图像时如何重复像素图