我有一个API,它返回以下内容:
{
'data' : {
players: [
{id: 1, name: 'harry'},
{id: 2, name: 'barry'} ...
],
},
'paging': {
current: 1,
totalPages: 10,
}
}
如何正确返回对象中的播放器以及分页信息,以便它们是单独的键?
getPlayers(type: string): Observable<Player[]> {
return this.get(myApiURL).pipe(
map(result => {
'players': result.data.map(player => {
player._dead = !!player.deathDate;
return player;
}),
}
);
);
最佳答案
接口(interface)
interface Player {
id;
name;
}
interface Paging {
current;
totalPages
}
interface HttpPlayer {
data: {
players: Player[]
};
paging: Paging;
}
interface UiPlayer {
id;
name;
current;
totalPages;
}
映射以合并播放器和分页(关于您的问题)
const mergePlayersWithPaging = (data: HttpPlayer): UiPlayer [] => data.players.map(player => Object.assign({}, player, data.paging))
映射到单独的播放器和分页(关于您的评论)
const mapHttpPlayerToPlayers = (httpPlayer: HttpPlayer): Player[] => httpPlayer.data.players;
const mapHttpPlayerToPaging = (httpPlayer: HttpPlayer):
使用映射(合并)
getPlayers(type: string): Observable<Player[]> {
return this.get(myApiURL).pipe(
map(mergePlayersWithPaging)
)
}
使用映射(单独)
getPlayers(type: string): Observable<Player[]> {
return this.get(myApiURL).pipe(
map(mapHttpPlayerToPlayers)
)
}
getPaging(type: string): Observable<Player[]> {
return this.get(myApiURL).pipe(
map(mapHttpPlayerToPaging)
)
}
关于javascript - 如何以正确的格式使用其他单独的分页数据以RxJS返回observable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60158440/