admin管理员组

文章数量:1389783

In my ponent I have a foreach loop that is fired when a client is selected. Inside this loop I have to call a function in the same ponent.

To do this I must use this.functionName() to call the function. But obviously this will not work inside the foreach loop since 'this' is no longer the ponent itself.

Does anyone have a solution for this?

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

In my ponent I have a foreach loop that is fired when a client is selected. Inside this loop I have to call a function in the same ponent.

To do this I must use this.functionName() to call the function. But obviously this will not work inside the foreach loop since 'this' is no longer the ponent itself.

Does anyone have a solution for this?

this.clientService.selectedClient.forEach(function(client) {
    this.getIntake(); // not working
});
Share Improve this question asked Dec 30, 2017 at 12:10 CS_studentCS_student 1074 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Use arrow functions

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

otherwise this will not point to the local class instance

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

本文标签: javascriptAngular call function in foreachStack Overflow