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

How to delay execution of function in Angular/Typescript

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

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

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

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

不过,我建议您重新考虑您的解决方案,那些互联网连接非常差的用户怎么办,结果可能需要超过 2 秒才能“到达”,您是否想惩罚速度很快的人?连接等待 2 秒(更新出现)?

如果您的数据作为承诺到达,请考虑使用异步/等待:

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

(请注意,这仅在通过 async 函数完成时有效,否则将作为传统 Promise 与 .then(() => ...) 一起使用)

或作为 Observable:

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