2016-05-17 78 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按预期工作