Stéphane GRILLON
Stéphane GRILLON

Reputation: 11862

angular 6 return result of forkJoin subscribe (rxJs 6)

Simple case and OK:

const observables = [];
for (let i = 0; i < this.originalData.length; i++) {
      observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
       };

forkJoin(...observables).subscribe(dataGroup => {
    console.log(dataGroup.id);
});

console is 1 2 3 4 5

More complexe case for me and KO:

private todo(foot) {
    const observables = [];
    for (let i = 0; i < this.originalData.length; i++) {
      observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
    };

    forkJoin(...observables).subscribe(dataGroup => {
      console.log(dataGroup);
      // How to put all dataGroup id in foot.param ?
    });

    return this.dashboardService.getFoo(foot);
}

the code execute this:

return this.dashboardService.getFoo(foot);

before this:

console.log(dataGroup);

How to wait end of subscribe and add/mofify all dataGroup id in foot.param before retun (at the end)?

Upvotes: 1

Views: 2555

Answers (1)

Nima Hakimi
Nima Hakimi

Reputation: 1392

The todo function should be async itself, so it should return an Observable:

private todo(foo): Observable<any> {
    const observables = [];
    for (let i = 0; i < this.originalData.length; i++) {
      observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
    };

    // notice that dataGroup is an array of latest value of all observables
   return forkJoin(observables).map((dataGroup: any[]) => {
      // do whatever you want to foo before calling the function
      // remember you need to also merge if getFoo returns an observable as well
      // but I assume it doesn't
      return this.dashboardService.getFoo(foo);
    });
}

Upvotes: 2

Related Questions