2

I am currently doing an online Angular course and I realized that RxJS is quite broadly used in web development. I was experimenting and I came across a nested map operator and I can kind of make sense of what is happening but I cant seem to find much information on it.

    this.productService.getProducts().pipe(
      map(products => 
        products.map(product => {
          const data = {...product.payload.val() as Product}; 
          return data;
        }))).subscribe(p => this.products = p)

So from my understanding is that the getProducts() function returns a list of Observables, then the outer map operator would emit an individual Observable into the inner map operator which then allows me to access the payload data from the http response? If this is correct, isnt there an easier/cleaner way of performing this functionality ?

  • 4
    Note that `products.map` is simply vanilla JS's [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) which still represents the (conceptually) same mapping operation RxJS also does. A 1:1 transformation of values. – VLAZ Jun 01 '22 at 17:12

1 Answers1

1

RxJS is quite a wonderful adventure when you start with it.

my guess from the code is the getProducts() returns an Observable that emits an Array of Products that are stored in product.payload.val

The map function then transforms the payload from GetProducts() to a typed array of Products.

It could also be done via:

this.productService.getProducts().pipe(
      map(products => {...product.payload.val() as Product[]})
)

https://stackblitz.com/edit/typescript-3jed7f?file=index.ts

Charlie V
  • 980
  • 1
  • 6
  • 12