0

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');
 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • It's all JavaScript in the end; TypeScript compiles (technically, transpiles) to JavaScript before the browser interprets it. – Heretic Monkey Jan 23 '17 at 18:30

2 Answers2

1

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?

eko
  • 39,722
  • 10
  • 72
  • 98
0

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); }
chrispy
  • 3,552
  • 1
  • 11
  • 19