Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs looping over returned array

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))
}
like image 249
altergothen Avatar asked Dec 08 '22 14:12

altergothen


2 Answers

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)))
)
like image 64
CozyAzure Avatar answered Dec 28 '22 06:12

CozyAzure


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)
);
like image 45
vicatcu Avatar answered Dec 28 '22 06:12

vicatcu