简体   繁体   English

Angular 2`this`引用在Promise中

[英]Angular 2 `this` reference in promise

My service has the following code: 我的服务具有以下代码:

....
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);
              });
          })
      }
  }
....

And in my page class, I am trying to access it as: 在页面类中,我尝试以以下方式访问它:

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);
    }

but in handleLogin , this.nav throws an error that this is undefined, and the console logs show this as blank and tt as undefined. 但在handleLoginthis.nav抛出了一个错误this是不明确的,并且控制台日志显示this空白和tt为未定义。 How do I reference this from within that function? 我如何从该函数中引用this

You need either to wrap the method call or call the bind method on it 您需要包装方法调用或在其上调用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);
}

or 要么

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);
}

There is a drawback to use the bind method in TypeScript since you lose type safety of the original function signature. 在TypeScript中使用bind方法有一个缺点,因为您失去了原始函数签名的类型安全性。 See this link for more details: 有关更多详细信息,请参见此链接:

Define handleLogin as a property rather than a method handleLogin定义为属性而不是方法

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

This will keep the this working as expected 这将使this工作按预期进行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM