Angular 2,如何使用setTimeout? [英] Angular 2, how to use setTimeout?

查看:732
本文介绍了Angular 2,如何使用setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在登录页面中,当他们提交页面时,我具有此功能:

In a login page, I have this function when they submit the page:

checkLogin(){
    this.x_userS.getLogin(this.x_userO.login_name, this.x_userO.pwd_plain).then(response => this.x_userO=response);
    (function(){
        setTimeout(() => {
            if (this.x_userO.login_status == "1") {
                this.x_companyS.getCompanyByUser(this.x_userO.user_id).then(response => this.x_companyO=response);
                (function(){setTimeout(() => {
                    this.x_userS.setUser(this.x_userO);
                    this.x_companyS.setCompany(this.x_companyO);
                    this.router.navigate(['HomePage']);
                }, 2000);
            })();
            }
            else {
                window.alert("oops");
            }
        }, 2000);
    })();
}

其中x_userS是登录服务,x_userO是用户对象.我正在尝试给诺言两秒钟,以便在处理数据之前返回数据.如果没有setTimeout,它将无法及时返回.

where x_userS is the login service and x_userO is the user object. I'm trying to give the promises two seconds to return the data before processing it. Without the setTimeout, it does not return it in time.

我尝试删除除警报以外的所有内容,并验证它是否在两秒钟后发生.但是,它无法识别function(){}中的任何其他内容,因此我认为我需要将我的所有服务和对象都传递进来.

I tried removing everything except the alert and verified it happened after two seconds. However, it doesn't recognize any of the other stuff inside function(){} so I believe I need to pass all my services and objects in.

有人知道该怎么做吗?

Does anyone know how to do this?

推荐答案

如果使用function(),则this.不会指向类中的变量. 在任何地方使用() =>代替.

If you use function(), then this. won't point to variables in your class. Use () => instead everywhere.

setTimeout()周围的(function(){ ... })()似乎还是多余的.

The (function(){ ... })() around setTimeout() seems to be redundant anyway.

这篇关于Angular 2,如何使用setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆