我已经从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)
);
}
}
现在我不确定如何将这些数据保存到数组中并将其显示在页面上。
答案 0 :(得分:2)
我认为您在提出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>
Documentation on using *ngFor。
这不是完美的,因为前面提到的无法很好地看到完整的JSON,但这绝对足以填补空白。如the head rush的评论中所述,您应该仔细阅读tutorial,以确保您了解所学内容。