[英]Display fetched data from api
我已經從API提取了數據,並且試圖將它們顯示為數組。 我能夠記錄請求數據並將其記錄到控制台中。
我無法將它們顯示到陣列中。
這是我的服務組件:
import {Injectable} from '@angular/core'; import {HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class EarthquakeService { constructor(private http: HttpClient) {} getEarthquakes(){ return this.http.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson'); } }
這是我在其中請求數據的應用程序組件:
import { Component, OnInit } from '@angular/core'; import {EarthquakeService} from '../../services/earthquake/earthquake.service'; @Component({ selector: 'app-earthquake-page', templateUrl: './earthquake-page.component.html', styleUrls: ['./earthquake-page.component.scss'] }) export class EarthquakePageComponent implements OnInit { earthquakes: string[]; eathqaukeTitle: string; constructor(private earthquakeService: EarthquakeService) { } ngOnInit() { this.getEarthqaukes(); } getEarthqaukes(){ this.earthquakeService.getEarthquakes().subscribe( (response) => console.log(response), (error) => console.log(error) ); } }
現在,我不確定如何將這些數據保存到數組中並在頁面上顯示它們。
我認為您在通過http
請求獲取數據時會丟失某些部分,請嘗試以下類似的操作。 該請求應類似於以下內容,無法從圖片中很好地得出JSON。
請求
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
public getEarthquakes(): Observable<any>{
return this.http.get('http://earthquake.usgs.gov/
earthquakes/feed/v1.0/summary/all_hour.geojson').pipe(map(data => data));
}
//only on two lines for SO readability
零件
public earthQuakes = [];
getEarthqaukes(){
this.earthquakeService.getEarthquakes().subscribe(
(response) => {
console.log(response)
this.earthQuakes = response.features; // whichever bit you are looking for.
},
(error) => console.log(error)
);
}
HTML
<div *ngFor="let shake of earthQuakes">
<span>{{shake}}</span>
</div>
如前所述,這不是完美的,無法很好地看到完整的JSON,但這絕對足以填補空白。 正如急於在評論中提到的那樣,您應該仔細閱讀本教程 ,以確保您了解所學內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.