如何延迟 Angular/Typescript 中函数的执行

问题描述

只能在这个上找到 JS 的东西。我只有重新加载页面元素的基本功能,我想将它们延迟 1-2 秒以等待 http 调用通过。我试过这个(从 rxjs 导入)但它根本不起作用

    setTimeout(function () {
      this.clearGroups();
      this.prepareRow();
      this.prepareGroups(); 
    },2000);

解决方法

正如@VLAZ 指出的那样,您需要一个箭头函数(以“关闭”正确的 this 范围,例如:

setTimeout(() => {
   this.clearGroups();
   this.prepareRow();
   this.prepareGroups(); 
},2000);

然而,我建议您重新考虑您的解决方案,对于互联网连接非常差的用户,结果可能需要超过 2 秒的“到达”时间,您是否想惩罚那些快速连接的用户?等待 2 秒钟(更新出现)?

如果您的数据作为承诺到达,请考虑使用 async / await:

await getData();
this.clearGroups();
this.prepareRow();
this.prepareGroups(); 

(请注意,这仅在通过 async 函数完成时才有效,否则使用带有 .then(() => ...) 的传统 Promise)

或作为 Observable:

getData().pipe(first()).subscribe(() => {
   this.clearGroups();
   this.prepareRow();
   this.prepareGroups(); 
});