Aetherix
Aetherix

Reputation: 2260

Angular 2: Use results of one http call to do another

I want to find work items for a given team. This needs to happen in two steps:

This is how I get the worklist:

WorklistService.ts

public getByTeamId(teamId): Observable<Worklist> {
    return this._http
        .get(url + "/" + teamId)
        .map(res => res.json().data as Worklist)
        .catch(this.handleError);
}

And here's how I get work items that are attached to that list:

WorkItemService.ts

public getByWorklistId(worklistId): Observable<WorkItem[]> {
    return this._http
        .get(url + "/" + worklistId)
        .map(res => res.json().data as WorkItem[])
        .catch(this.handleError);
}

Then in my Component I'd need to somehow chain these calls. Here's what I have so far:

this._worklistService
    .getByTeamId(teamId)
    .subscribe(
        worklist => {
            if (worklist) {
                this._workItemService
                    .getByWorklistId(worklist._id)                    
                    .subscribe(
                        workItems => this.workItems = workItems,
                        error => console.log("Could not retrieve work items"));
            }
        },
        error => console.log("Could not retrieve worklist"));

Is this really the best way to chain these calls or is there a more elegant way?

Upvotes: 2

Views: 63

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202296

You could leverage the flatMap operator to do that:

this._worklistService
    .getByTeamId(teamId)
    .flatMap(
      worklist => {
        if (worklist) {
          return this._workItemService
                 .getByWorklistId(worklist._id);
        } else {
          return Observable.throw('worklist is undefined');
        }
      })
    .subscribe(
       workItems => this.workItems = workItems,
       error => console.log("Could not retrieve work items"));

This operator allows to plug another request when the first one completes into the asynchronous data flow.

Upvotes: 1

Related Questions