0

I'll explain my situation.

I have a external javascript file that has a function like:

searchForSomething(id, callbackFunction);

That method 'searchForSomething' is async and the return is call the callbackFunction. In my component.ts I have:

declare function searchForSomething(id, callbackFunction): any;
...
message: string;
id: number;
...
next(){
  searchForSomething(this.id, this.print);
}

print(result: string) {
  this.message = result;
  console.log(result);
}
...

ERROR: Uncaught ReferenceError: 'message' is not defined

But neither 'this' is defined. My code works using this test:

next(){
  //searchForSomething(this.id, this.print);
  this.print('result as a mock.');
}

I guess that I have a context or scope problem here. I got that when my ts method is called by external javascript, I lost angular references.

What's the rigth way to use call back function into ts? Or I need to review my javascript method to remove 'function' parameter? But it is async, so I can't just remove the callbackFunction, put a return and wait for a result.

3

1 Answer 1

5

This is an issue about scope. When you pass callback function, the function loses its scope.

So, you can convert print to arrow function to make the function's scope where it is defined:

print = (result: string) => {
  this.message = result;
  console.log(result);
}

UPDATE

Also you can use .bind(this) to assign the scope manually if you don't want to use arrow functions.

next(){
  searchForSomething(this.id, this.print.bind(this));
}
Sign up to request clarification or add additional context in comments.

4 Comments

You can read more on this issue here: typescriptlang.org/docs/handbook/functions.html Section: "this and arrow functions"
@Robert Thanks for extending the answer.
@HarunYılmaz thanks, That works! And I undertood a bit more about Javascript and Angular. I used the bind solution.
Actually the arrow functions are more useful in this context because they keep scope themselves where they are defined. Glad to help btw :)

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.