简体   繁体   English

Angular CLI和JavaScript回调函数

[英]Angular cli and javascript callback function

I'll explain my situation. 我会解释我的情况。

I have a external javascript file that has a function like: 我有一个具有以下功能的外部javascript文件:

searchForSomething(id, callbackFunction);

That method 'searchForSomething' is async and the return is call the callbackFunction. 该方法“ searchForSomething”是异步的,返回值称为callbackFunction。 In my component.ts I have: 在我的component.ts中,我有:

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. 但是都没有定义“ this”。 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. 我知道,当ts方法被外部javascript调用时,我丢失了角度引用。

What's the rigth way to use call back function into ts? 在ts中使用回调函数的正确方法是什么? Or I need to review my javascript method to remove 'function' parameter? 或者我需要查看我的JavaScript方法来删除“功能”参数? But it is async, so I can't just remove the callbackFunction, put a return and wait for a result. 但这是异步的,所以我不能只删除callbackFunction,放一个返回并等待结果。

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转换为arrow函数,以使函数的作用域定义如下:

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

UPDATE UPDATE

Also you can use .bind(this) to assign the scope manually if you don't want to use arrow functions. 如果不想使用箭头功能,也可以使用.bind(this)手动分配作用域。

next(){
  searchForSomething(this.id, this.print.bind(this));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM