Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, how to use setTimeout?

Tags:

angular

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

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.

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?

like image 993
Yifan Avatar asked Jul 08 '16 03:07

Yifan


1 Answers

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

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

like image 163
Günter Zöchbauer Avatar answered Oct 05 '22 09:10

Günter Zöchbauer