2016-05-17 84 views
0
參考

我的服務具有以下代碼:角2`this`在承諾

.... 
isAuthenticated(){ 
     var tt = this; 
     if(tt.current_user){ 
      return Promise.resolve(tt.current_user,false); 
     }else{ 
      return new Promise(resolve => { 
       this.http.get(this.api.urlBase+this.api.apiBase+'/Individuals/me', 
          {withCredentials: true}) 
       .map(res=>res.json()) 
       .subscribe((data) => { 
        tt.current_user = data; 
        resolve(data,false); 
       },(err)=>{ 
        reject(err,true); 
       }); 
      }) 
     } 
    } 
.... 

而在我的頁面類,我試圖訪問它:

constructor(){ 
... 
let tt = this; 
individual.isAuthenticated().then(this.handleLogin); 
... 
} 
... 
handleLogin(d,err){ 
     console.log("This: ",this); 
     console.log("This: ",tt); 
     this.nav.present(this.loading); 
    } 

但在handleLoginthis.nav拋出錯誤,this未定義,並且控制檯日誌顯示this爲空白,tt爲未定義。如何從該函數中引用this

回答

1

您需要用包裝方法調用或致電bind方法它

constructor() { 
    ... 
    let tt = this; 
    individual.isAuthenticated().then((data) => { // <---- 
    this.handleLogin(data) 
    }); 
    ... 
} 
... 
handleLogin(d,err){ 
    console.log("This: ",this); 
    console.log("This: ",tt); 
    this.nav.present(this.loading); 
} 

constructor() { 
    ... 
    let tt = this; 
    individual.isAuthenticated().then(this.handleLogin.bind(this)); 
    ... 
} 
... 
handleLogin(d,err){ 
    console.log("This: ",this); 
    console.log("This: ",tt); 
    this.nav.present(this.loading); 
} 

有,因爲你失去了原有的功能簽名的類型安全使用的打字稿中bind方法的缺點。請參閱此鏈接瞭解詳情:

0

定義handleLogin作爲財產而非方法

//handleLogin(d,err){ 
handleLogin = (d,err) => { 
    console.log("This: ",this); 
    console.log("This: ",tt); 
    this.nav.present(this.loading); 
} 

這將保持this按預期工作