Dhiraj Narayan Singh
Dhiraj Narayan Singh

Reputation: 37

How to call Typescript method from Javascript callback method - Angular2

I am using angular2 my issue is that I am not able to call component method from javascript callback here is the code snippet.

 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');
 }

Upvotes: 0

Views: 902

Answers (2)

eko
eko

Reputation: 40647

One of the ways to access global this is to use bind like this:

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

Right now this piece of js code coreApi.callApi(request, this.afterCallApi); as you know will call this.afterCallApi but note that you are using the function without paranthesis () this means that this.afterCallApi will be invoked as an inner function of callApi, with callApi's inner this binded to afterCallApi.

If you want to test it, do a console.log(this); inside afterCallApi with your original code. You will see that this is an object and not the globalthis.

In order to give the "access" to afterCallApi we simply bind the this which refers to the global this.

Also check this great post for more info: How to access the correct `this` inside a callback?

Upvotes: 1

chrispy
chrispy

Reputation: 3612

If you define your function using the arrow format, it will maintain the scope of this for you.

Example:

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

Upvotes: 0

Related Questions