0

I need to do a query to 2 separate endpoints to provide the objects needed for my component.

No Endpoint Response
1 /registry/colors {"colors":["red","green","blue","orange"]}
2 /color/{colorName} {"name":"red", "details":["detail1","detail2", "detail3"]}

For each color in the colors array, I need to call the color details endpoint and collect all of those color details into an array of Colors.

getColors(): Observable<Color[]> {
  return this.http.get<ColorRegistry>(this.registryUrl).pipe(
    map((registry:ColorRegistry) => registry.colors.concatMap((colorName: string) => {
      return this.http.get<Color>(this.colorUrl+"/"+colorName);
    }))
  )
}

I would like the above method to return the following:

[
 {"name":"red", "details":["detail1","detail2", "detail3"]},
 {"name":"green", "details":["detail1","detail2", "detail3"]},
 {"name":"blue", "details":["detail1","detail2", "detail3"]},
 {"name":"orange", "details":["detail1","detail2", "detail3"]}
]

Obviously I'm going about this the wrong way, I'm looking for the correct way to do the nested requests with observables.

2 Answers 2

2

You are in the right direction.

Try the following changes.

  1. Replace the map operator with a higher order mapping operator like switchMap.
  2. Use JS Array#map and replace each entry in the colors array property with the response from the second call.
  3. Use forkJoin to trigger the requests in parallel and merge the results in the end.
getColors(): Observable<Color[]> {
  return this.http.get<ColorRegistry>(this.registryUrl).pipe(
    switchMap((registry: ColorRegistry) => {
      return forkJoin(
        registry.colors.map((colorName: string) => 
          this.http.get<Color>(`${this.colorUrl}/${colorName}`)
        )
      ) as Observable<Color[]>;    // <— assert type here
    })
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is telling me that Observable<unknown[]> is not assignable to type 'Observable<Color[]>'.
@Joel: I’ve adjusted the post to add type assertion.
0
registryUrl = '/registry/colors';

colorUrl(color) {
  return `/color/${color}`;
}

return this.http.get<ColorRegistry>(this.registryUrl).pipe(
  map(registry => from(registry.colors))
  forkJoin(color => this.http.get<Color>(this.colorUrl(color)))
);

1 Comment

This is telling me Argument of type 'Observable<never>' is not assignable to parameter of type 'OperatorFunction<unknown, Color[]>'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.