Search code examples
angularrxjsrxjs5

Observable of array, find index of value


I'm writing an Angular app that gets a selection of stores from a service, as an Observable.

When the user clicks a marker on the map, I want to get the index of the store in the array that lives inside the Observable.

stores: Observable<Store[]>;

ngOnInit() {
    this.stores = http.get<Store[]>('URL');
}

onMarkerClick(event) {
   const geopoint = event.geopoint;
   //How can I get the index where store.geopoint === event.geopoint?
}

Solution

  • For filtering the stores from the array you do:

    this.storesCollection.filter(store => store.geopoint === event.geopoint); // -1 if not found
    

    And for transforming the Observable to an Array use map:

    this.stores$.map((stores: Stores[]) => this.storesCollection = stores)
    

    You don't need to do subscribe() because http returns a hot observable, always firing regardless of there being a subscriber or not