如何在AngularJS中获得超时或延迟工作



当谈到AngularJS时,我是一个十足的傻瓜。我需要一些帮助来获得一条信息,显示一段时间,然后离开。

以下代码将法官的分数写入数据库,然后阻止该法官再次得分,直到分数从数据库中清除为止。当法官提交他们的分数时,我希望在法官小组下面出现一条消息,类似于";好的&";。目前,当设置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>

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

首先,如果您可以选择,并且不必拘泥于更新遗留代码,那么如果您使用新的Angular,而不是旧的AngularJS,生活会轻松得多。您不必太担心摘要周期,以及AngularJS是否检测到您对变量值所做的更改。

无论如何,您编写的代码告诉angular在3秒后将isLoading设置为true,而不是在3秒后设置。你需要做的是:

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

也就是说,首先将其设置为true,然后在3秒钟后将其设置成false

您需要这样做:

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

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

最新更新