【发布时间】:2020-03-05 09:43:01
【问题描述】:
我目前正在构建一个 Angular 应用程序,我在其中向 api 发出请求,并将响应映射到两个不同的数组。我可以在app.components.ts 中使用这些数据,但我会根据需要制作新组件。我如何在组件之间共享数据以确保组件始终拥有最新数据,因为我还需要定期调用 API。
我在 SO 和一些 youtube 视频上看到了一些答案,但我只是没有完全理解它。
我的服务代码是
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
private _earthquakePropertiesSource = new BehaviorSubject<Array<any>>([]);
private _earthquakeGeometrySource = new BehaviorSubject<Array<any>>([]);
constructor(private readonly httpClient: HttpClient) {
}
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)
};
})
);
}
在我的app.component.ts 中使用如下:
properties: Array<any>;
geometries: Array<any>;
constructor(private readonly earthquakeService: EarthquakeService) {
}
ngOnInit() {
this.earthquakeService.getEarthquakeData().subscribe(data => {
this.properties = data.properties;
this.geometries = data.geometries;
this.generateMapData();
});
}
generateMapData() {
for (const g of this.geometries) {
const tempData: any = {
latitude: g.coordinates[0],
longitude: g.coordinates[1],
draggable: false,
};
this.mapData.push(tempData);
}
任何帮助将不胜感激。
【问题讨论】:
标签: angular rxjs observable angular-httpclient behaviorsubject