2017-01-23 110 views
0

我正在使用angular2我的問題是,我無法從javascript回調調用組件方法這裏是代碼段。如何從Javascript回調方法調用Typscript方法 - Angular2

declare var CORE_FACTORY:any; 

// CORE_FACTORY Defined in javascript file which I've included in index.html and it's gets loded perfectly. 

let coreApi = CORE_FACTORY.setupApiByDomain(Domain.QA); 
coreApi.addUserEventListener(apiName, ApiEvent.ON_ANY_EVENT,this._userCallBack); 
coreApi.callApi(request, this.afterCallApi); 

afterCallApi(status, responceObject) { 
      this.postCreateInstrument(accountNumber); //Getting error right here. 
} 

public postCreateInstrument(accountNumber:string) { 
     alert('test'); 
} 
+0

它的所有的JavaScript到底;在瀏覽器解釋它之前,TypeScript會將其編譯(技術上,編譯)爲JavaScript。 –

回答

1

的方式之一,進入全球this是使用bind這樣的:

coreApi.callApi(request, this.afterCallApi.bind(this, status, responceObject)); 

眼下這段js代碼coreApi.callApi(request, this.afterCallApi);,你知道會調用this.afterCallApi但請注意,您所使用的()這意味着將調用this.afterCallApi作爲callApi的內部函數,callApi的內部this綁定到afterCallApi

如果您想測試它,請使用您的原始代碼在afterCallApi之內執行console.log(this);。你會看到this是一個對象,而不是全局的this

爲了給「訪問」afterCallApi我們只需bindthis這是指全球this

還要檢查這個偉大的職位更多的信息:How to access the correct `this` inside a callback?

+1

太棒了!它的工作..非常感謝你.. –

+0

請你詳細說明邏輯..請... –

+0

@DhirajSingh肯定我會更新答案 – echonax

0

如果您使用箭頭格式定義功能,它會保持this範圍內爲您服務。

實施例:

var afterCallApi = (status, response) => { this.postCreateInstrument(accountNumber); }