Yifan Yifan - 5 months ago 41
AngularJS Question

Angular 2, how to use 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);
})();
}


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?

Answer

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.