[英]How to call Typescript method from Javascript callback method - Angular2
我正在使用angular2,我的問題是我無法從javascript回調中調用組件方法,這是代碼段。
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');
}
其中的訪問途徑全球this
是使用bind
是這樣的:
coreApi.callApi(request, this.afterCallApi.bind(this, status, responceObject));
現在,這段js代碼coreApi.callApi(request, this.afterCallApi);
如您所知,將調用this.afterCallApi
但請注意,您正在使用不帶this.afterCallApi
()的函數,這意味着this.afterCallApi
將作為callApi
的內部函數調用,而callApi
的內部this
綁定到afterCallApi
。
如果要測試,請執行console.log(this);
在afterCallApi
並帶有您的原始代碼。 您將看到this
是一個對象,而不是全局this
。
為了給在“訪問” afterCallApi
我們只是bind
了this
是指在全球this
。
還可以查看此精彩文章以獲取更多信息: 如何在回調中訪問正確的`this`?
如果您使用箭頭格式定義功能,它將保持的范圍this
給你。
例:
var afterCallApi = (status, response) => { this.postCreateInstrument(accountNumber); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.