AnchovyLegend AnchovyLegend - 1 month ago 6
TypeScript Question

Calling internal component function is throwing undefined error

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!');
}
}

Answer

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));