kabus
kabus

Reputation: 909

How to wait till nested forkjoin is finished?

i have a problem with a nested forkjoin, when i try to subscribe pull, it's getting back my data, but i can see that getitem3 is still running. How to wait till all functions are finished before subscribe

see example

pull(id) {
  return Observable.forkJoin(
    this.getitem1(id),
    this.getitem2(id),
    this.getitem3(id)
  );
}



getitem3(id) {
  let url = 'https://host3/get/' + id;
  let observableBatch = [];

  return this.http.get(url).map(res => res.json()).map(data => {
    data.posts.data.forEach((item) => {
      observableBatch.push(this.getImageUrl(item.id));
    })
    return Observable.forkJoin(observableBatch);
  })
}


getitem2(id) {
  let url = 'https://host2/get/' + id;
  let observableBatch = [];

  return this.http.get(url).map(res => res.json()).map(data => {
   data.posts.data.forEach((item) => {
     observableBatch.push(this.getImageUrl(item.id));
   });
   return Observable.forkJoin(observableBatch);

  });
}

 getitem1(id) {
  let url = 'https://host1/get/' + id;
  let observableBatch = [];

  return this.http.get(url).map(res => res.json()).map(data => {
    data.posts.data.forEach((item) => {
      observableBatch.push(this.getImageUrl(item.id));
    });
    return Observable.forkJoin(observableBatch);
  });
}

getImageUrl(id) {
  let url = 'https://localhost/image/' + id;
  return this.http.get(url).map(res => res.json()).map(data => {
    console.log('done');
  });
}

Upvotes: 0

Views: 3440

Answers (1)

Nikolai
Nikolai

Reputation: 489

I think your methods getitemN() returns Observable <Observable<any>>. And when you subscribing you just calling first observable, to call anothers you can use flatMap instead of map.

.flatMap(data => {
                data
                    .posts
                    .data
                    .forEach((item) => {
                        observableBatch.push(this.getImageUrl(item.id));
                    })
                return Observable.forkJoin(observableBatch);
            })

So in this case you will get only Observable <any>.

Here is also helpful information: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http. FlatMap is in "Dependent calls" section.

Upvotes: 3

Related Questions