I've encountered a peculiar issue while working on a test project. It seems that I am unable to access values in an array.
pokemonStats$: Observable<PokemonStats[]>;
getPokemonStats(id: number): any {
this.pokemonStats$
.pipe(take(1))
.subscribe(stats => {
console.log(stats instanceof Array);
console.log('length', stats.length);
console.log('du', stats);
console.log('test', stats[1]);
});
}
Here is the unexpected output:
https://i.sstatic.net/ObOKW.png
I'm puzzled by this behavior. A colleague has suggested that it might be an array-like structure, which prompted me to add the 'instanceof' log. Any assistance would be greatly appreciated.
EDIT: Here is the code where the array is populated.
this.pokemonStats$ = this.getAllPokemonStats(ids);
getAllPokemonStats(ids: number[]): Observable<PokemonStats[]> {
const pokemonArray: PokemonStats[] = [];
ids.forEach(id => {
const url = 'https://pokeapi.co/api/v2/pokemon/' + id;
this.http.get(url)
.pipe(take(1))
.subscribe((data: PokemonStatsAPI) => {
pokemonArray.push({
id: data.id,
name: data.name,
speed: data.stats[0].base_stat,
hp: data.stats[5].base_stat,
attack: data.stats[4].base_stat,
defense: data.stats[3].base_stat
});
});
});
return of(pokemonArray);
}