我最初有这段代码
this.gameService.getAll()
.pipe(map(data => data['hydra:member']))
.subscribe( (games: Game[]) => this.games = games );
但是如果我想从json响应中检索更多属性,则有人告诉我这样做
this.gameService.getAll()
.pipe(map(data => data['hydra:member']))
.subscribe(result => [result["hydra:member"], result['hydra:totalItems']]);
但是如何将以下代码添加到上面的代码中:
(games: Game[]) => this.games = games );
并将totalItems映射到变量。
答案 0 :(得分:0)
使用以下行:pipe(map(data => data ['hydra:member'])),它将仅包含hydra:member中的数据。
this.games是否包含API或hydra:member的所有数据?
尝试:
this.gameService.getAll().subscribe((games: Game[]) => {
this.games = games;
this.totalItems = games['hydra:totalItems']
});
答案 1 :(得分:0)
我会尝试定义有效负载(我打算从调用中返回的对象),并使用类型安全性将该对象填充出去以帮助我。
这样的事情。
// you can just add more properties later if you like
export interface IGamesGetAllResponseObject {
games: any[]; // or better yet define the game object so it isn't any
totalGames: number;
}
// now define a function that will map the response to the intended object
export mapGamesGetAllToReponse(data): IGamesGetAllResponseObject {
return {
games: data['hydra:member'],
totalGames: data['hydra:totalItems'],
};
}
...
//then use it like this
this.gameService.getAll()
.pipe(map(mapGamesGetAllToReponse))
.subscribe( (result: IGamesGetAllResponseObject) => {
this.games = result.games;
this.totalGames = result.totalGames;
});
我还没有100%检查过我所有的语法,但是它应该非常适合您。
我还将考虑在服务本身中进行所有映射,而不是在您订阅的地方进行。通过这样做,您可以包含有关所需数据以及如何将其映射到服务的逻辑,并且组件仅请求所需数据。
答案 2 :(得分:0)
您可以通过调用相同属性从json响应中获取多属性,因此上述代码将为:
this.gameService.getAll().pipe(map(result =>
{
this.games = result["hydra:member"] ;
this.totalItems = result['hydra:totalItems'];
}
)).subscribe();
,然后调用“ this.games”和“ this.totalItems”内联订阅块。