2016-10-19 63 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

相关问题