2016-05-17 15 views
0

に私のサービスは、次のコードがあります、角度2 `this`参照約束

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

が、handleLoginに:

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

そして、私のページクラスでは、私はそれにアクセスしようとしていますthis.navthisが未定義であり、コンソールログにはthisが空白、ttは未定義と表示されるというエラーが発生します。どのようにその機能内からthisを参照するのですか?

答えて

1

を期待どおりに動作し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); 
} 

あなたは、元の関数のシグネチャの型の安全性を失うので、活字体でbindメソッドを使用する欠点があります。詳細については、このリンクを参照してください:

0

プロパティとしてhandleLoginを定義むしろ

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

方法よりも、これは

関連する問題