Angular 调用内部组件函数引发未定义错误
我试图使用Angular 调用内部组件函数引发未定义错误,angular,typescript,Angular,Typescript,我试图使用this前缀在回调函数的作用域内调用我的组件中的内部函数。出于某种原因,这会引发未定义的函数错误。你知道为什么吗?提前谢谢 import { Component } from '@angular/core'; @Component({ selector: 'page-login', templateUrl: 'login.html', providers: [] }) export class LoginPage {
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!');
}
}
这是因为
此
未在回调函数的范围内引用您的组件。你必须使用
或bind()
感谢您的回复,您建议的第一个实现可以用于任何回调函数吗?或者回调函数必须返回一个承诺才能工作吗?这与返回值无关,
=>
为我相信的任何回调捕获此
。
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));