Couim
Couim

Reputation: 747

Call external function angular 2

I've a problem with facebook API,

I would like to call a function but I'm located in Facebook.api function so my function is not recognized because I'm encapsulated in Facebook object. Here is my code :

export class MyClass {

constructor(platform:Platform) {
}
function1(number_likes:number) {
        var elem = document.getElementById('number_of_likes');
        elem.innerHTML = ""+number_likes;
   }

query_fan_numbers() {
       var pageId = "81221197163?fields=fan_count";
       Facebook.api(pageId, null)
      .then(function(success) {
         this.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
      }
    }

My error is something like that : TypeError: Cannot read property 'function1' of null

How can I call the function1 function in my class ?

Upvotes: 0

Views: 39

Answers (1)

eko
eko

Reputation: 40647

As @jonrsharpe mentioned

You can either use a fat arrow:

query_fan_numbers() {
       var pageId = "81221197163?fields=fan_count";
       Facebook.api(pageId, null)
      .then((success)=> {
         this.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
      }
    }

or the the plain old javascript trick to store this in a variable to use later.

query_fan_numbers() {
       var that = this;
       var pageId = "81221197163?fields=fan_count";
       Facebook.api(pageId, null)
      .then(function(success) {
         that.function1(parseInt(JSON.stringify(success.fan_count))); //Here's the error
      }
    }

Upvotes: 1

Related Questions