DEV Community

Ricardo Torres
Ricardo Torres

Posted on • Originally published at ricardo-torres.me on

Angular - Rxjs - Operator mergeAll

MergeAll is represented by 2 Observables, the first one is named a higher-order Observable and the second one is an Observable that will depend upon each item of the higher-order Observable.

MergeAll is useful when you have a scenario to perform operations or searches by each item that is coming from the first Observable, so you are going to have one observable for each item.

Let me illustrate this with an example to make it clear.

Example:

We have 2 Observables:

1- I only have fruits names inside the the order higher Observable:

const fruits$ = new Observable((observer) => {
      observer.next('Cereza');
      observer.next('Mandarina');
      observer.next('Pera');
      observer.complete();
    });
Enter fullscreen mode Exit fullscreen mode

2-The second Observable contains all the fruits with name, description, price and its image, it is located in a service name productService:

getProductsByName(name: string): Observable<any> {
    let headers = new HttpHeaders();
    headers = headers.set(
      'X-Master-Key',
      '$2b$10$ghNHmZWM5nvdrV5tDL6akuKN6JanJ9/iG9vAa4F1yJF8X/ccv3o9C'
    );
    const url = 'https://api.jsonbin.io/v3/b/62b9ef87192a674d291cb521';
    const data = this.httpClient.get<RootObject>(url, { headers: headers });
    return data.pipe(
      map((x) => {
        return x.record;
      }),
      map((y) => {
        let filtered = y.filter((c) => c.name === name);
        return filtered.length > 0 ? filtered[0] : null;
      })
    );
  }
Enter fullscreen mode Exit fullscreen mode

The challenge consist in reading the order higher observable and call the method getProductsbyName and searchs all the details for every product in the list of the Observable and show it in a gallery.

Final Result:

Structure of the Observable with MergeAll.

Final Code:

import { Component, OnInit } from '@angular/core';
import { map, mergeAll, Observable, of } from 'rxjs';
import { Record } from 'src/app/model/record';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
})
export class ProductListComponent implements OnInit {
  record: Record[] = [];
  constructor(private productService: ProductService) {}

  ngOnInit(): void {
    this.getProducts();
  }

  addItem(name: string) {}

  getProducts(): void {
    const fruits$ = new Observable((observer) => {
      observer.next('Cereza');
      observer.next('Mandarina');
      observer.next('Pera');
      observer.complete();
    });

    fruits$
      .pipe(
        map((x) => {
          return this.productService.getProductsByName(`${x}`);
        }),
        mergeAll()
      )
      .subscribe((x) => {
        this.record.push(x);
      });
  }
}

Enter fullscreen mode Exit fullscreen mode

Live Demo

Download Code

Top comments (0)