我有下面的url https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson,我想从一个以角表示的服务中提出一个http请求。
数据是一个具有一系列特征的对象。在特征中,有4个对象-类型、属性、几何学和id。我想将属性、和几何学对象存储在我的应用程序中自己的数组中。
我该怎么做?
我在service.ts中的代码是:
public getEarthquakeData(): Observable<any[]> {
return this.httpClient.get<any[]>(this.url);
}我知道如何从组件调用这个服务,但我不知道如何循环访问/访问我想要保存的数据。
任何帮助都将不胜感激。
发布于 2020-03-04 15:32:11
您发布的url的响应如下:
{
"type": "",
"metadata": [],
"features": [
{
"type": "",
"properties": {},
"geometry": {},
"id": ""
}
],
"bbox": []
}您对提取properties数组和geometry数组感兴趣。如果您想共享此功能,在您的服务中这样做是有意义的。
为此,您需要在管道中的RxJS map操作符中转换响应。
public getEarthquakeData(): Observable<{ properties: [], geometries: []}> {
return this.httpClient.get<any>(this.url).pipe(
// this will run when the response comes back
map((response: any) => {
return {
properties: response.features.map(x => x.properties),
geometries: response.features.map(x => x.geometry)
};
})
);
}然后,当您在组件中订阅此函数时,您将收到如下所示的对象:
{
"properties": [],
"geometries": []
}component.ts
properties: [];
geometries: [];
ngOnInit() {
this.earthquakeService.getEarthquakeData().subscribe(data => {
this.properties = data.properties;
this.geometries = data.geometries;
});
}发布于 2020-03-04 15:31:18
尝试:
import { map } from 'rxjs/operators';
.......
properties: Array<any>;
geometries: Array<any>;
ngOnInit() {
this.earthquakeService.getEarthquakeData().pipe(
// pluck the features array from the object
map(data => data.features),
).subscribe(features => {
// this will give you the array of objects you would like
this.properties = features.map(feature => feature.properties);
this.geometries = features.map(feature => feature.geometry);
});
}发布于 2020-03-04 17:07:31
这里是一个快速的堆栈闪电战,我收集了如何处理这个问题。如果您不想使用服务来存储您的数据,只需在订阅之前将http调用上的管道移动到您的组件上,然后更改为map。
尽管如此,我强烈建议您将结果存储在服务中,并使用路由解析器触发数据获取,然后可以在实际组件中使用数据订阅。
https://stackblitz.com/edit/angular-ccqrju
如果您还想以其他方式存储和使用原始数据,这里的服务路由还保留了其他一些内容。
https://stackoverflow.com/questions/60529289
复制相似问题