Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!');
      }
    }
like image 995
AnchovyLegend Avatar asked May 16 '26 04:05

AnchovyLegend


1 Answers

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));
like image 194
artem Avatar answered May 18 '26 21:05

artem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!