RxJs looping over returned array

20,588

Solution 1

Why don't just pipe a map() ?

this.dataService.getItemData()
    .pipe(
        map(itemData => {
            return itemData.map(value => {
                return new ListingItem(value.label, value.market, value.name);
            })
        })
    )
    .subscribe((listingItem) => {
        console.log(listingItem) // gives an array of listingItem
    });

Note that .map() is a JavaScript's native array function, you will use it to transform the data, by looping over each item of the array

Just for a one-liner:

.pipe(
    map(itemData => itemData.map(value => new ListingItem(value.label, value.market, value.name)))
)

Solution 2

I'm still learning Observables myself, but I think you can create an Observable from an Array like I did in this StackBlitz: https://stackblitz.com/edit/angular-tbtvux

In a nutshell (in Angular 6):

import { from, pipe } from 'rxjs';
...
let observable = from([10, 20, 30])
  .subscribe(v => console.log(v));

So maybe you can pipe the switchMap operator on your observable which returns an array, something like this:

import { switchMap } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val))
);

... and then you could use map after that like so:

import { switchMap, map } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val)),
  map(val => val * 42)
);

... at least that seems to work in my aforementioned StackBlitz.


Update: I think the flatMap operator also works similarly, with a single operator:

yourArrayObservable$.pipe(
  flatMap(val => val * 42)
);
Share:
20,588
altergothen
Author by

altergothen

Updated on December 10, 2020

Comments

  • altergothen
    altergothen over 3 years

    Is there a better way using RxJS operators to loop over an array returned from an observable than this to emit a new individual ListingItem?

    onGetItemData(){
    this.dataService.getItemData().subscribe((itemData) =>
    {
      this.itemDataJSON = itemData;
      this.itemDataJSON.forEach(function (value) {
        let new_listing = new ListingItem(value.label,value.market,value.name);
        console.log(new_listing);
      });
     });
    }
    

    The API returns a single array containing the items, so I am unable to use .map to access itemData.name

    //-- DataService --// 
    getItemData(){
     return this.http.get(this._URL, { headers })
            .pipe(map((res: Listings) => res.items))
    }