过去几天我一直在尝试学习Angular 9,并想重新制作一个神奇宝贝应用程序。
我现在遇到的问题是,当我尝试遍历pokemon数组时,它在屏幕上显示[object Object]。
现在我知道ngFor只能迭代Arrays,这就是为什么我遇到这个问题,但是我似乎无法解决它。
这是代码:
pokemon.service:
@Injectable({
providedIn: 'root',
})
export class PokemonService {
private pokemonsUrl = 'https://pokeapi.co/api/v2/pokemon';
constructor(private http: HttpClient) {}
getPokemons() {
return this.http.get(this.pokemonsUrl);
}
}
pokemon.component:
pokemons: any[] = [];
errorMessage: string;
constructor(private pokemonService: PokemonService) {}
ngOnInit(): void {
this.pokemonService.getPokemons().subscribe(
(data) => {
this.pokemons = data['results'];
console.log(this.pokemons);
},
(err: any) => console.log(err),
() => console.log('all done getting pokemons')
);
}
html:
<div *ngIf="pokemons">
<div *ngFor="let pokemon of pokemons">
{{pokemon}}
</div>
</div>