![](/img/trans.png)
[英]How do I display returned JSON from RESTful API call with JavaScript
[英]How to display a single JavaScript Object / JSON item from API Call
我從已經設法在表格中顯示的 API 調用中獲取數據。 現在,當您單擊表中的某個項目時,我想顯示該項目的更詳細視圖。
因此,當我打開鏈接 localhost:4200/detail/12 時,我想顯示來自 id=12 的 object 的數據。 但我無法弄清楚如何做到這一點。
我目前從 people.component.html
...
<tr *ngFor="let data of data" routerLink="/detail/{{data.person_id}}">
<td>{{data.person_id}}</td>
<td>{{data.name}}</td>
</tr>
...
API的數據為JSON格式:
[{"person_id":"1","name":"Tom"},{"person_id":"2","name":"Clarissa"},{"person_id":"4","name":"Micky"},...]
但顯示的(在瀏覽器中)數據記錄為 JavaScript 對象:
0:
person_id: 1
name: "Tom"
2:
person_id: 2
name: "Clarissa"
3:
person_id: 4
name: "Micky"
...
那么我該如何調整 people-detail.component.ts 和 people-detail.component.html 以僅顯示所選項目的數據(例如,person_id = 12)而不是所有項目(這就是發生的情況目前)?
這就是我的 people-detail.component.ts 目前的樣子
...
export class PeopleDetailComponent implements OnInit {
public data: any = []
constructor(
public http: HttpClient,
private route: ActivatedRoute) { }
getData(){
const person_id = +this.route.snapshot.paramMap.get('person_id');
const url ='http://localhost:4000/api/allpeople'
this.http.get(url).subscribe
(data => this.data = data);
}
ngOnInit() : void{
this.getData()
}
這是我目前的 people-detail.component.html:
<div *ngFor="let data of data">
<div>
<span>id1: </span>
{{data.regulation_id}}
</div>
</div>
我會使用旋轉變壓器 go 。
首先聲明詳細視圖的路由:
const routes: Routes = [
{
path: 'detail/:id',
component: PersonComponent,
resolve: { message: PersonResolver }
}
];
您可以在任何想要獲取人員詳細信息的地方使用解析器(在加載組件之前獲取數據的可重用方式
然后在路由上創建解析器:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRoute, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { of } from "rxjs";
import { delay } from "rxjs/operators";
@Injectable()
export class PersonResolver implements Resolve<Person> {
constructor(private route: ActivatedRoute) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
const id = route.paramMap.get('id');
const url = 'your url here';
return this.http.get(url);
}
}
你也可以看看這個選擇內聯stackblitz
您必須為數據創建接口:
export interface iUsers {
person_id: string;
name: string;
}
那么您必須將代碼更改為:
public data: iUsers[] = []
this.http.get<iUsers[]>(url).subscribe((res)=>{
this.data = res
console.log(this.data)
})
如下設置點擊監聽器。
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of data" (click)="onClickHandler(data.person_id)">
<td>{{data.person_id}}</td>
<td>{{data.name}}</td>
</tr>
</tbody>
</table>
這會將所選項目的 id 傳遞給處理程序方法。具有所選 id 的 object 將存儲在“selected”變量中。
onClickHandler(id)
{
this.selected=this.data.find(item=>{
if(item['id']===id)
{
return true;
}
return false;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.