首页 > 解决方案 > 如何在 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;
    }
  }

不幸的是,代码只循环了一次,为什么???

标签: javascriptangularsettimeoutsetinterval

解决方案


setTimeout在不同的范围内调用函数。this不指向对象。你需要绑定对象

setTimeout(this.reloadFunction.bind(this), pageOrder[this.id].duration * 1000);

推荐阅读