I am currently building an Angular application where I make a request to an api, and I map the repsonse to two different arrays. I can use this data in my app.components.t
Service:
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
properties = new BehaviorSubject>([]);
geometries = new BehaviorSubject>([]);
constructor(private readonly httpClient: HttpClient) {
loadEarthquakeData().
}
public loadEarthquakeData(): Observable<{ properties: [], geometries: []}> {
return this.httpClient.get(this.url).pipe(
tap((response: any) => {
this.properties.next(response.features.map(x => x.properties);
this.geometries.next(response.features.map(x => x.geometry));
})
).toPromise();
}
Component:
private _subscription: Subscription;
constructor(private readonly earthquakeService: EarthquakeService) {
}
ngOnInit() {
this.generateMapData();
}
ngOnDestroy() {
if (this._subscription) {
this._subscription.unsubscribe();
}
}
generateMapData() {
this._subscription = this.earthquakeService.geometries.subscribe(geometries => {
for (const g of this.earthquakeService.geometries.getValue()) {
const tempData: any = {
latitude: g.coordinates[0],
longitude: g.coordinates[1],
draggable: false,
};
this.mapData.push(tempData);
}
});
}
For that, you need Angular Services
They are singletons that can act like a shared state. What you want to do is to store your data inside the service, and then call the service from both of your components and listen to the service's BehaviorSubject.