【问题标题】:Angular 4 setInterval unexpected behaivorAngular 4 setInterval 意外行为
【发布时间】: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


    【解决方案1】:

    我认为正在发生的事情是时间问题。

    setIntervalwill 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;
        });
    }
    

    在不知道您的应用程序如何加载角色的情况下,我不知道这是否可能,但如果您可以这样做,肯定会更干净。

    【讨论】:

    • 我很喜欢这个想法,感谢您的回复。我试试看
    • @RunFranks525 如果有效,请将答案标记为正确:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2017-04-20
    • 1970-01-01
    • 2018-02-15
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多