How can I convert a multi http request into a component-store effect in ngrx

241 Views Asked by At

I'm new to ngrx and component-store, and I need to make a variable amount of parallel http requests (based on how many ids I have) to a service, sending a different ID for each one, and in the end, adding all the results into a single one.

Let's say I have something like this (might have some mistakes, I just wrote it down as an example):

public apiUrl = 'example.com/prices/books';
public bookIds$ = new BehaviorSubject<number[]>([1, 2, 3, 4]);
public totalAmount = 0;

constructor(private _http: HttpClient) {}

ngOnInit():void {
    this.bookIds$.subscribe(data => {
        this.totalAmount += this.getTotalAmount(data)
    })
}

public getTotalAmount(idArray: number[]): number {
    let subTotal = 0; // to reset the totalAmount before adding book prices
    for (int i = 0; i < idArray.length; i++)
    {
        this.http.get(`${URL}/${idArray[i]}`)
        .subscribe(response => {
            subTotal += response;
        })
    }
    return subTotal
}

How can I convert that method into a component-store effect? I need an example to understand what rxjs operators should I use and how, inside an effect like this:

this.effect((bookIds$: Observable<number[]>) => { 
    return bookIds$.pipe( 
        // do the forkJoin 
        // do some patchState with the final combined result 
    ) 
}
1

There are 1 best solutions below

2
Brandon Taylor On

forkJoin takes an array of observables (or an object) and returns an array of values (or an object) in the order the observables were defined when all of the observables emit a value:

forkJoin([
  this.httpClient.get<SomeType>(url1),
  this.httpClient.get<SomeType>(url2),
  this.httpClient.get<SomeType>(url3),
])
.subscribe(responses => {
  const [ value1, value2, value3 ] = responses;
});

It's similar in functionality to Promise.all(). You can also add error handling on each observable to catch failures. Something to keep in mind is that forkJoin won't emit anything if any of the observables error out.