Javascript 角度4设置间隔意外行为
我在角度4分量的setInterval中有这个问题。似乎范围错误,没有按预期更新组件。我已经了解到箭头函数是维护组件作用域的解决方案 似乎角色已明确设置(结果将按预期在模板文件中更新),并且setInterval确实通过我假定的对clearInterval()的调用停止运行。但是,我希望设置为false(初始化为true)的this.loadingActions没有正确更新。如果在该块中调试,则组件上的this.loadingActions成员未定义,而console.log(this.loadingActions)打印为false,并且UI本身未更新 roleSetup()是通过ngOnInit()调用的 我也尝试过类似的东西,我知道这是不合适的,但仍然并没有运气的范围Javascript 角度4设置间隔意外行为,javascript,angular,setinterval,Javascript,Angular,Setinterval,我在角度4分量的setInterval中有这个问题。似乎范围错误,没有按预期更新组件。我已经了解到箭头函数是维护组件作用域的解决方案 似乎角色已明确设置(结果将按预期在模板文件中更新),并且setInterval确实通过我假定的对clearInterval()的调用停止运行。但是,我希望设置为false(初始化为true)的this.loadingActions没有正确更新。如果在该块中调试,则组件上的this.loadingActions成员未定义,而console.log(this.load
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);
我认为现在发生的是时间问题
setInterval
。因此,setInterval
之后的所有代码在提取角色之前运行,因此检查角色是否存在的if语句的计算结果总是false
它在模板中更新的原因是Angular使用,这是一个库,在执行任何浏览器事件后向Angular发出警报。(如果您知道angular.js,您可以将其视为一种工具,在设置间隔之后自动运行摘要循环)
在不删除角色轮询的情况下,只需将逻辑移动到setInterval
。这样,一旦加载了角色,就可以更新loadingActions
boolean
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;
});
}
在不知道应用程序是如何加载角色的情况下,我不知道这是否可行,但如果您能这样做,肯定会更干净。我很喜欢这个想法,谢谢您的回复。我会给你一个机会try@RunFranks525如果有效,请将答案标记为正确:-)
roleSetup() {
this.userDataService.getUserRole().then(role => {
this.role = role;
this.loadingActions = false;
});
}