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

前端 未结 6 648
甜味超标
甜味超标 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:50

    The service method doesn't need return an Observable:

    public getEarthquakeData(): Observable<{ properties: [], geometries: []}> {
        return this.httpClient.get(this.url).pipe(
         // this will run when the response comes back
        tap((response: any) => {
          _earthquakePropertiesSource.next(response.features.map(x => x.properties));
          _earthquakeGeometrySource.next(response.features.map(x => x.geometry));
        })
    });
    

    And the component:

    ngOnInit() {
        combineLatest(
            this.earthquakeService._earthquakePropertiesSource,
            this.earthquakeService._earthquakeGeometrySource
        ).subscribe(data => {
          this.properties = data[0];
          this.geometries = data[1];
          this.generateMapData();
    });
    }
    

提交回复
热议问题