I am trying to call an internal function within my component within the scope of a callback function using the this prefix. For some reason, this is throwing an undefined function error. Any ideas why this is? Thanks in advance!
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!');
}
}
It's because this does not refer to your component in the scope of callback function. You have to use arrow function
this.Service.getLoginStatus(response => {
if(response.status == 'connected') {
this.printHelloWorld(); //throws undefined error
}
});
or bind()
this.Service.getLoginStatus(function(response) {
if(response.status == 'connected') {
this.printHelloWorld(); //throws undefined error
}
}.bind(this));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With