javascript - 将字符串转换为 Angular 中的函数调用

标签 javascript angular typescript

我得到了一个函数名,想在 Angular 类(.ts 文件)中调用它。 eval() 不是一个选项。

我试过使用 window[functionName] ,但它失败了,猜测是因为窗口上下文在类之外

有什么想法吗?

最佳答案

这很容易。例如,getData 是您的函数名称。

getData() {
  // your code goes here...
}

functionName = 'getData'; // function name as a string

现在你可以像下面这样调用这个函数:

this[functionName]();

关于javascript - 将字符串转换为 Angular 中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466212/

相关文章:

angular - 刷新 Angular 6 项目页面时出现 403 错误

typescript - 如何在 TypeScript 中为具有动态属性的对象定义类型

reactjs - 属性...在类型 'IntrinsicAttributes & ...' 上不存在

typescript - 如何配置 tsconfig.json 将多个源文件夹中的文件输出到单个 flat outDir?

node.js - RxJS if-else 就像管道过滤

javascript - 尝试替换文档中的每个 href

javascript - html Canvas 中的蒙版图像

javascript - 在 react 表的单元格中将字符串呈现为 html

Angular Animation 在 IE11 和 Firefox 中不转换(在 Chrome 中工作)

javascript - 过滤分页传递参数到异步 ember 数据关系请求