How to use BehaviourSubjects to share data from API call between components in Angular?

前端 未结 6 543
甜味超标
甜味超标 2021-01-28 22:21

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

6条回答
  •  情话喂你
    2021-01-28 22:41

    Edit 1

    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);
          }
        });
      }
    
    

    Original

    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.

提交回复
热议问题