我试图找到一个解决方案来显示我从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
我试着寻找解决方案来迭代结果,但找不到一个。
您需要从您的服务的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>