CodyBugstein
CodyBugstein

Reputation: 23322

How do you nest API calls in Angular 2?

I would like to get data from one Restful service and then use that data when getting data from another restful service.

The flow is basically

http.get("http://service.com/firstservice")
.onresponse(function(res){
     http.get("http://service.com/firstservice/" + res)
     .onresponse(function(res){
          console.log(res);
          // display in view
     }
}
)

How can this be done in Angular 2?

Upvotes: 0

Views: 229

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202266

You leverage the flatMap operator:

return http.get("http://service.com/firstservice")
    .map(res => res.json())
    .flatMap((data) => {
      return http.get("http://service.com/firstservice/" + res);
    })
    .map(res => res.json());

The map operator is necessary if you want to extract the JSON payload of responses.

Upvotes: 2

Related Questions