2016-10-19 5 views
1

this接頭辞を使用して、コールバック関数のスコープ内で自分のコンポーネント内の内部関数を呼び出そうとしています。何らかの理由で、これは未定義の関数エラーを投げています。これはなぜですか?前もって感謝します!内部コンポーネント関数を呼び出すと、定義されていないエラーが発生しています

import { Component } from '@angular/core'; 

    @Component({ 
     selector: 'page-login', 
     templateUrl: 'login.html', 
     providers: [] 
    }) 
    export class LoginPage { 

     constructor() { 
     console.log('construct called'); 
     } 

     checkLoginStatus() { 
     this.Service.getLoginStatus((response) => { 
      if(response.status == 'connected') { 
       this.printHelloWorld(); //throws undefined error 
      } 
     }); 
     } 

     printHelloWorld() { 
     console.log('hello world!'); 
     } 
    } 

答えて

3

thisは、コールバック機能の範囲でコンポーネントを参照していないためです。あなたは最初の実装は、あなたが任意のコールバック関数のための作業を提案することができ、応答アルテムためarrow function

 this.Service.getLoginStatus(response => { 
     if(response.status == 'connected') { 
      this.printHelloWorld(); //throws undefined error 
     } 
    }); 

または

 this.Service.getLoginStatus(function(response) { 
     if(response.status == 'connected') { 
      this.printHelloWorld(); //throws undefined error 
     } 
    }.bind(this)); 
+0

bind()感謝を使用する必要がありますか?コールバック関数は、それが動作するために約束を返さなければなりませんか? – AnchovyLegend

+2

これは戻り値には関係しません。 '=>'は、私が信じるコールバックに対して 'this'を捕捉します。 – artem

+0

、助けてくれてありがとう! – AnchovyLegend

関連する問題