【发布时间】:2018-04-10 21:11:51
【问题描述】:
我在 Angular 4 组件中遇到了 setInterval 的问题。范围似乎是错误的,并且没有按预期更新组件。我已经阅读了箭头函数是维护组件范围的解决方案。
看来该角色已确定(结果在模板文件中按预期更新)并且 setInterval 实际上通过我假设是对 clearInterval() 的调用而停止运行。但是,我想设置为 false(初始化为 true)的 this.loadingActions 没有正确更新。如果我在该块中调试组件上的 this.loadingActions 成员未定义,而 console.log(this.loadingActions) 打印为 false 并且 UI 本身仍未更新。
roleSetup() 通过 ngOnInit() 调用
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);
【问题讨论】:
标签: javascript angular setinterval