foreach中的角度调用函数

时间:2017-12-30 12:10:51

标签: javascript angularjs angular foreach

在我的组件中,我有一个在选择客户端时触发的foreach循环。在这个循环中,我必须在同一个组件中调用一个函数。

要做到这一点,我必须使用this.functionName()来调用该函数。但显然这在foreach循环中不起作用,因为'this'不再是组件本身。

有人有解决方案吗?

this.clientService.selectedClient.forEach(function(client) {
    this.getIntake(); // not working
});

1 个答案:

答案 0 :(得分:4)

使用箭头功能

this.clientService.selectedClient.forEach((client) => {
    this.getIntake(); // not working
});

否则this将不会指向本地类实例

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions