2

I have a problem with Observables in Angluar2 app. Let assume hypothetical situation that I need to make two separate http calls. One call depends directly on the result of the other. The code looks like this:

this.http.get('http://kalafior/group/'+id)
    .map(res => res.json())
    .subscribe(group => {
        //url depends on previous call result
        this.http.get('http://kalafior/group/'+group.id+'/posts')
            .map(res => res.json())
            .subscribe((res) => {
                console.log(res);
            });
    });

There are nested subscribe() calls which I want to get rid of.

ayeo
  • 482
  • 1
  • 4
  • 16
  • Same type of question, you can check it here to get a better understanding http://stackoverflow.com/questions/35268482/chaining-rxjs-observables-from-http-data-in-angular2-with-typescript?rq=1 – pd farhad Jul 15 '16 at 13:28

2 Answers2

4

flatMap was created exactly for this kind of scenarios.

this.http.get('http://kalafior/group/'+id)
    .map(res => res.json())
    .flatMap(group => this.http.get('http://kalafior/group/'+group.id+'/posts') )
    .map(res => res.json())
    .subscribe((res) => {
       console.log(res);
    });
});
Daniel Pliscki
  • 1,913
  • 16
  • 24
-1

What you can do, is to take advantage of .do() function from Rxjs. Take a look here

uksz
  • 18,239
  • 30
  • 94
  • 161