簡體   English   中英

Angular 2`this`引用在Promise中

[英]Angular 2 `this` reference in promise

我的服務具有以下代碼:

....
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

您需要包裝方法調用或在其上調用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);
}

在TypeScript中使用bind方法有一個缺點,因為您失去了原始函數簽名的類型安全性。 有關更多詳細信息,請參見此鏈接:

handleLogin定義為屬性而不是方法

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

這將使this工作按預期進行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM