2016-07-08 136 views
10

在登錄頁面,我有這樣的功能,當他們提交頁面:Angular 2,如何使用setTimeout?

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,它不會及時返回。

我試着除去警報以外的所有東西,並驗證它在兩秒鐘後發生。但是,它不承認function(){}中的其他任何東西,所以我相信我需要通過我所有的服務和對象。

有沒有人知道如何做到這一點?

+0

我相信你使用$ timeout – user5680735

+0

$ timeout僅適用於Angular 1;請參閱http://stackoverflow.com/a/40402767/132374 –

回答

21

如果您使用function(),那麼this.將不會指向您班級中的變量。 改爲使用() =>代替。

(function(){ ... })()約在setTimeout()無論如何似乎是多餘的。

+1

謝謝,我刪除了函數()部分,它與'this'一起工作正常。我正在關注一個例子,他使用函數(j)傳遞一個數字j,我想如果我不想傳遞任何東西,我只需將函數作爲()。 – Yifan

+1

對於這個問題,YEP箭頭函數爲您提供了正確的背景。謝謝! –