Getting sub data for Observable<Object[]>

I have a service that returns Observable<Object[]>. Each Object has subObjectId. I would like to set object's property subObject with the subObject data that should come from other service. How do I do that?

Object {
subObjectId: number;
subObject: SubObject;
}

this.serviceB.getSubObject(subObjectId) returns Observable<SubObject>

Am I doing it correctly?

this.serviceA.getObjects().pipe(
map((objects) => objects.map((object) => ({...object, subObject: this.serviceB.getSubObject(object.subObjectId).pipe(take(1)).subscribe()}))
)

Upvotes: 0

Views: 222

Answers (1)

Barremian
Barremian

Reputation: 31105

You are almost close. Instead of subscribing to each service B request individually, you can use forkJoin to combine multiple observables. And since you have pipe(take(1)), the forkJoin will emit after all the service B requests emits at least once.

Try the following

this.serviceA.getObjects().pipe(
  switchMap(objects =>
    return forkJoin(objects.map(object => this.serviceB.getSubObject(object.subObjectId).pipe(take(1)))).pipe(
      map(subObjects => subObjects.map((subObject, index) => ({
        subObjectId: objects[0]['subObjectId'],
        subObject: subObject
      })))
    );
  )
).subscribe(
  res => { },
  err => { }
);

The output will be of the form

[
  { 
    subObjectId: 1, 
    subObject: /* response from this.serviceB.getSubObject(1) */
  },
  { 
    subObjectId: 2, 
    subObject: /* response from this.serviceB.getSubObject(2) */
  },
  ...
]

Upvotes: 1

Related Questions