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');
 }
1
  • It's all JavaScript in the end; TypeScript compiles (technically, transpiles) to JavaScript before the browser interprets it. Commented Jan 23, 2017 at 18:30

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.