[英]how to access data from json response angular
I am trying to access data from a json server using observables, the api returns the response in the following format.我正在尝试使用 observables 从 json 服务器访问数据,api 返回以下格式的响应。
{
"status": "success",
"data": {
"players": [
{
"id": "1",
"national_id": "29706242100538",
"name": "Muhammed",
"club_id": 1,
"gov": "Giza",
"age_level_id": 5,
"weight": 57,
"gender": "M"
},
{
"id": "2",
"national_id": "29706242100538",
"name": "Muhammed",
"club_id": 1,
"gov": "Giza",
"age_level_id": 5,
"weight": 57,
"gender": "M"
},
{
"id": "3",
"national_id": "29706242100538",
"name": "Muhammed",
"club_id": 1,
"gov": "Giza",
"age_level_id": 5,
"weight": 57,
"gender": "M"
}
]
}
}
getPlayers(): Observable<Player[]> {
return this.http.get<Player[]>(baseURL + 'allplayers').pipe(catchError(this.processHTTPMsgService.handleError));
}
players: Player[];
this.playrService.getPlayers().subscribe(players => (this.players = players), errmess => this.errMess = <any>errmess);
Ps: this.players is a variable of type Player "a class that I created like this. Ps:this.players 是 Player 类型的变量“我这样创建的 class。
export class Player {
id:number;
national_id:number;
name:string;
club:string;
gov:string;
age_level:string;
weight:number;
gender:string;
};
This method puts the full response in the "players" variable "the status and the data", I know I am missing something but whatever I tries keeps leading me to the same place.这种方法将完整的响应放在“玩家”变量“状态和数据”中,我知道我错过了一些东西,但无论我尝试什么,都会把我带到同一个地方。
I expect the players "this.players" to contain only the data from the json response, to be able to access values like "id, name, etc.." in the html.我希望播放器“this.players”仅包含来自 json 响应的数据,以便能够访问 html 中的“id、name 等”等值。
Assign the property players from the response as below.从响应中分配属性播放器,如下所示。
this.playrService.getPlayers().subscribe(response => (this.players = response.data.players), errmess => this.errMess = <any>errmess);
Loop the data in html as below.如下循环html中的数据。
<table>
<thead>
<th>Id</th>
<th>National Id</th>
<th>Name</th>
</thead>
<tbody>
<tr *ngFor="let player of players">
<td>{{player.id}}</td>
<td>{{player.national_id}}</td>
<td>{{player.name}}</td>
</tr>
</tbody>
</table>
I think that you need to define the correct type
like this:我认为您需要像这样定义正确的
type
:
interface DataResponse { status: string; data: {players: Player[]}; }
Than to fix the get method like this:而不是像这样修复get方法:
getPlayers(): Observable<Player[]> { return this.http.get<DataResponse>(baseURL + 'allplayers').pipe( map(res => res.data.players), catchError(this.processHTTPMsgService.handleError) ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.