首页 > 解决方案 > 如何在 AngularJS 中超时或延迟工作

问题描述

谈到 AngularJS,我完全是个菜鸟。我需要一些帮助才能让消息显示一段时间然后离开。

以下代码将裁判的分数写入数据库,然后阻止该裁判再次评分,直到分数从数据库中清除。我希望在评委提交分数时在评委面板下方显示一条消息,例如“OK!”。目前,它会在 isLoading = true 设置时显示,但只是非常短暂,因为正如您从下面的代码中看到的那样,它会变为 false。我需要它自动变为 false,但仅在 3 秒左右之后。

async send(): Promise<any> {
try {
  this.isLoading = true;
  const star: { isValid: boolean } = await this.judgeService.submitScoreIsValid(this.id).toPromise();
  if (star.isValid === true) {
    await this.judgeService.write(this.id, {score: this.currentScore}).toPromise();
    this.status = true;
  } else {
    this.status = false;
  }
} catch (e) {
  console.log(e);
} finally {
  this.isLoading = false;
}
}

我希望 isLoading 等于 true 但仅持续大约 3 秒。我怎样才能做到这一点?

我试过去:

this.isLoading=true;    
$timeout(function(){ this.isLoading=false; }, 3000);

但它没有用,它只是保持不变并且在 3 秒后不会消失。任何人都可以帮忙吗?

我的前端是这样的:

<div *ngIf="isLoading">
     <h5>OK!</h5>
</div>

*编辑以反映以下答案之一的建议所做的更改。

标签: javascriptangularjs

解决方案


你需要这样做:

$timeout(() => this.isLoading = false, 3000);

非箭头函数创建一个新的this上下文,箭头函数将保留外部this


推荐阅读