Reputation: 19
i am looking for a way to get a query during a foreach with angular. I have a table like this:
players = [
{
id: 'af948a0a-66be-44b1-af85-7ccd1a289df0',
pseudo: 'DocEo.AG',
age: '31',
twitch: '',
youtube: false,
facebook: false,
twitter: '',
stats: [],
}];
I would like at the foreach, get the stats via the id of the person and push in my table, but for the moment without success. Here is my code for the moment that does not work.
ngOnInit() {
this.players = this.teamService.players;
this.statUser();
}
statUser() {
this.players.forEach(function(element) {
console.log(element.id);
this.getStats('element.id');
});
}
getStats(idUser) {
this.http.get(this.urlIdTest + idUser).subscribe((data) => {
this.getStat = data;
});
}
EDIT: I have a new problem, everything works fine but I have this error message in the console:http://prntscr.com/p2kvu8 My array: http://prntscr.com/p2kwpf
Upvotes: 0
Views: 436
Reputation: 9124
Just a little side note, please avoid vanilla functions within Angular Components. Always use Arrow-functions. Vanilla functions change the scope of this
this.players.forEach(function(element) {
console.log(element.id);
this.getStats('element.id'); // the this here
});
this.players.forEach(element => {
console.log(element.id);
this.getStats('element.id'); // is not the same here
});
Upvotes: 0
Reputation: 5462
You are passing id as 'element.id'
(string) modify code like:
...
statUser() {
this.players.forEach(function(element) {
console.log(element.id);
this.getStats(element.id);
});
}
...
Update 1
You can optimize your code by passing complete object and then assign stats in it.
statUser() {
this.players.forEach((player) => {
this.getStats(player);
});
}
getStats(player) {
this.http.get(this.urlIdTest + player.id).subscribe((data) => {
player.stats = data;
});
}
Upvotes: 1