我在Angular 4组件中使用setInterval存在此问题。看起来范围是错误的,并且没有按预期更新组件。我已经读过,箭头函数是维护组件范围的解决方案。
看来角色是明确设置的(结果在模板文件中按预期更新),而setInterval实际上确实通过我认为是对clearInterval()的调用停止运行。但是,我希望将其设置为false(初始化为true)的this.loadingActions未正确更新。如果我在该块中调试,则组件上的this.loadingActions成员未定义,而console.log(this.loadingActions)打印为false,并且UI本身仍未更新。
通过ngOnInit()
调用roleSetup()roleSetup() {
this.fetchRole = setInterval(() => {
this.role = this.userDataService.getUserModel().role;
}, 1000)
if (this.role !== "") {
console.log("hullo");
this.loadingActions = false;
console.log(this.loadingActions);
clearInterval(this.fetchRole);
console.log(this);
debugger;
}
console.log(this.loadingActions);
console.log(this.role);
}
我也尝试过这样的事情,我知道这是不合适的,但仍然没有运气范围
this.fetchRole = setInterval(() => {
this.role = this.userDataService.getUserModel().role;
if(this.role !== "") {
this.loadingActions = false;
}
}, 1000)
if (this.role !== "") {
clearInterval(this.fetchRole);
}
console.log(this.role);
console.log(this.loadingActions);
答案 0 :(得分:2)
我认为发生的事情是时间问题。
setInterval
will run the passed function asynchronously。因此,setInterval
之后的所有代码在获取角色之前运行,因此检查角色是否存在的if语句始终评估为false
。
它在模板中更新的原因是因为Angular使用Zone.js,这是一个在任何浏览器事件执行完毕后警告Angular的库。 (如果您了解angular.js,您可以将其视为在setInterval
之后自动运行摘要周期的工具
如果不删除角色的轮询,只需将逻辑移到setInterval
即可。这样,一旦加载了角色,您就可以更新loadingActions
布尔值。
roleSetup() {
this.fetchRole = setInterval(() => {
this.role = this.userDataService.getUserModel().role;
if (this.role !== "") {
this.loadingActions = false;
clearInterval(this.fetchRole);
}
}, 1000)
}
但如果您可以更新userDataService
以获得一个根据承诺返回角色的函数,那可能会更好:
roleSetup() {
this.userDataService.getUserRole().then(role => {
this.role = role;
this.loadingActions = false;
});
}
在不知道你的应用程序如何加载角色的情况下,我不知道这是否可行,但如果你能这样做,它肯定会更清晰。