typescript 有没有一种方法可以使用 *ngFor来迭代对象数组

piv4azn7  于 2023-04-13  发布在  TypeScript
关注(0)|答案(2)|浏览(232)

我试图找到一个解决方案,以显示我从API接收的整体结果。目前只有一个游戏及其详细信息可以在应用程序中看到。
我的服务看起来像这样:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, map } from 'rxjs';
import { environment } from 'src/environments/environment';

import { Igameschart } from '../interfaces';

interface IgamesData {
  results : [{
name : string,
released : number,
platform : string,
background_image : string,
rating : number
    }]
}

export interface IGamesService{
  getGames(genre:string):Observable<Igameschart>
}
@Injectable({
  providedIn: 'root'
})
export class GamesService implements IGamesService {
  constructor(private httpClient: HttpClient) { }
  getGames(genre:string):
  Observable<Igameschart>{
    return this.httpClient.get<IgamesData>(
      `${environment.baseUrl}api.rawg.io/api/games?` +
      `genres=${genre}&key=${environment.appId}`
    ) .pipe(map(data => this.tarnsformToIgamesData(data)))
  }
private tarnsformToIgamesData(data:IgamesData):
  Igameschart{
    return {
      name: data.results[0].name,
      released: data.results[0].released,
      platform: data.results[0].platform,
      image:data.results[0].background_image,
      rating:data.results[0].rating
    }
  }
}

它以这种方式嵌入到视图中:

<div class="container" *ngIf="gamesloaded">
    <div>
        <img [src]='gamesloaded.image' height="249px" width="512em">
    </div>
    <div>
        <div id="gdata">{{gamesloaded.name}}</div>
        <div id="gdata"> {{gamesloaded.released | date:'fullDate'}}</div>
        <div id="gdata"> {{gamesloaded.platform}}</div>
        <div id="gdata">{{gamesloaded.rating}}</div>
    </div>
</div>
<div *ngIf="!gamesloaded">
    <span>No data available</span>
</div>

代码可以在这里找到-〉https://stackblitz.com/edit/angular-cbt8ka
我试图寻找迭代结果的解决方案,但找不到。

w8f9ii69

w8f9ii691#

你需要从你的服务的tarnsformToIgamesData方法返回Igameschart数组,这样你的服务看起来就像

export interface IGamesService{
  getGames(genre:string):Observable<Igameschart[]>
}
@Injectable({
  providedIn: 'root'
})
export class GamesService implements IGamesService {
  constructor(private httpClient: HttpClient) { }
  getGames(genre:string):
  Observable<Igameschart[]>{
    return this.httpClient.get<IgamesData>(
      `${environment.baseUrl}api.rawg.io/api/games?` +
      `genres=${genre}&key=${environment.appId}`
    ) .pipe(map(data => this.tarnsformToIgamesData(data)))
  }
private tarnsformToIgamesData(data:IgamesData):
  Igameschart[]{
    return data.results.map(item=>{return {
      name: item.name,
      released: item.released,
      platform: item.platform,
      image:item.background_image,
      rating:item.rating
    }});
  }
}

那么你的组件应该是

gamesloaded: Igameschart[]
  constructor(private gamesService : GamesService) {
  }
  ngOnInit() {
    this.gamesService.getGames('action')
    .subscribe((data) => this.gamesloaded = data)
  }

你的HTML将会是

<div *ngFor='let game of gamesloaded'>
  <div>
    <img [src]='game.image' height="249px" width="512em">
  </div>
  <div id="gdata">{{game.name}}</div>
  <div id="gdata"> {{game.released | date:'fullDate'}}</div>
  <div id="gdata"> {{game.platform}}</div>
  <div id="gdata">{{game.rating}}</div>
</div>
vhipe2zx

vhipe2zx2#

为要显示的数据创建子组件,在父组件中执行 *ngFor。
在父组件中,您必须有一个空数组来表示数据的数据类型(示例游戏:int [];),在ngOnInit中,您将服务的数据分配给空数组。

超文本标记语言

<*ngFor="let game of games">
  <app-game-view [game]="game"></app-game-view>

父组件

games: Game[] = [];

constructor(private gameService: GameService) {}

ngOnInit(): void {
   this.gameService.getGames().subscribe((games) => (this.games = games));
}

在children组件中,您可以单独填充每个游戏的HTML,但是父组件的 *ngFor是在object上循环的。
所以基本上父组件遍历对象数组,子组件显示对象。

相关问题