2016-10-19 62 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 
     } 
    }); 

bind()

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

感謝您的答覆阿爾喬姆,可以先執行你的建議的任何回調函數的工作?或者回調函數是否必須返回一個承諾才能工作? – AnchovyLegend

+2

這與返回值無關,'=>'爲任何我相信的回調捕獲'this'。 – artem

+0

明白了,謝謝你的幫助! – AnchovyLegend

相關問題