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

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

    You can include a property on the service that will hold this data, and subscribe to it instead. I'm assuming you'll have a timed interval checking for new responses - which can then just update the value of the property in the service.

    export interface earthQuakeResponse {
        properties: Array
        geometries: Array
    }
    
    export class EarthQuakeService {
        private _earthQuakeResponse = new BehaviorSubject([]);
        readonly earthQuakeResponse = this._earthQuakeResponse.asObservable();
    
        public getEarthquakeData(): Observable {
                return this.earthQuakeResponse;
        }
    
        //call this method when you want to update your data
        private updateData() {
                this.httpClient.get(this.url).subscribe(
                        response => {
                            this._earthQuakeResponse.next({
                                properties: response.features.map(x => x.properties),
                                geometries: response.features.map(x => x.geometry)
                            });
                        });
        }
    }
    

提交回复
热议问题