对象对象ngFor角度9 / Typescript

时间:2020-05-09 19:48:06

标签: angular typescript

过去几天我一直在尝试学习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>

1 个答案:

答案 0 :(得分:2)

似乎数组的每个元素都是具有属性nameurl的对象。

enter image description here

您可以直接在模板中访问属性。尝试以下

<div *ngIf="pokemons">
  <div *ngFor="let pokemon of pokemons">
    {{ pokemon.name }}
  </div>
</div>