簡體   English   中英

如何從Javascript回調方法中調用Typescript方法-Angular2

[英]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我們只是bindthis是指在全球this

還可以查看此精彩文章以獲取更多信息: 如何在回調中訪問正確的`this`?

如果您使用箭頭格式定義功能,它將保持的范圍this給你。

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM