2

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

  • Retrieve the worklist that was generated for that team
  • Retrieve the work items that are attached to that worklist

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.