D
D
D2022-04-08 08:38:40
JavaScript
D, 2022-04-08 08:38:40

How to work with arrays in RxJs?

packages.forEach((pack) => {
    this.packageService.getPackage(pack.id)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((newPack: Package) => {
        this.verbosePackages.push(newPack);
        this.sharedPackagesService.updatePackages(this.verbosePackages);
      })
  }


getParameters(): void {
    this.verbosePackages.forEach((pack) => {
      this.packageParameters = this.packageParameters.concat(pack.packageParameters);
    })
    this.getParameterVisibilities();
  }


I have two such functions.
How can I make the getParameters() function only run after each array element in the first function in the loop has made a request to the server, received a response from it, and added that response to the verbosePackages array?
You can, of course, write a crutch that will check the length of the packages and verbosePackages arrays before running the getParameters() function, but this is clearly a very bad solution.
In general, I have many similar situations when I need to work with some kind of array, but I don’t know if all the necessary data came from the backend. What solutions exist to call some kind of trigger that will notify that all database queries have been completed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2022-04-08
@sxenguri

getParameters(ids: (string|number)[]): Observable<MyResult[]> {
  return forkJoin(ids => ids.map(id => this.packageService.getPackage(id)))
}

A typical parallel query with a batch of results.
You don't need a subscription with adding results to an array, promises don't need to be dragged anywhere at all, they immediately ignored strange dudes with promises and a lot of meaningless code :)
Inside this.packageService.getPackage , you may have to do error handling, if an error occurs in forkJoin, then the whole bundle will break, well, just like in the case of Promise.all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question