2016-11-13 66 views
0

我已經與Facebook API的一個問題,調用外部函數角2

我想調用一個函數,但我位於Facebook.api功能,所以我的功能不被識別,因爲我封裝在Facebook對象。這裏是我的代碼:

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 
     } 
    } 

我的錯誤是類似的東西:TypeError: Cannot read property 'function1' of null

我如何可以調用function1功能在我的課?

+2

你爲什麼要用'function(success){'而不是'(成功)=> {',哪個*會*綁定this'? – jonrsharpe

回答

1

由於@jonrsharpe提到

您可以用一份豐厚的箭頭:

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 
     } 
    } 

或普通的老JavaScript的伎倆來存儲this在變量以後使用。

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 
     } 
    } 
+1

好吧謝謝它現在的作品:) –