Home > database >  Rxjs: map each element in an array field from an observable of object with another observable
Rxjs: map each element in an array field from an observable of object with another observable

Time:04-12

I have a method called getTransactionDetails(id:string), and it returns an Observable of TransactionDetails object

getTransactionDetails(id:string):Observable<TransactionDetails> 

The TransactionDetails object looks like this:

class TranscationDetails{
    id:string;
    accessCode: string;
    veggiesList: Array<Veggie>;
    meatList: Array<Meat>;
}

The Veggie object looks like this:

class Veggie{
    id: string;
    name: string;
}

I have another method called getVeggieSummary(veggieId: string), and it returns an Observable of VeggieSummary:

getVeggieSummary(veggiesId:string):Observable<VeggieSummary>

VeggieSummary looks like this

class VeggieSummary{
    id:string;
    name:string;
    color:string;
    kind:string;
}

I would like to call getTransactionDetails(1), and transform all the Veggies elements in the veggiesList to be VeggieSummary and return an VeggieSummary array.

This is what I have

getTransactionDetails(1)
.flatMap(transactionDetails=>
    transactionDetails.veggiesList
       .map(veggie=>getVeggieSummary(veggie.id)))
.subscribe(result=>
    console.log(result)
)

Currently, result is an Observable<VeggieSummary> and the inner observable is not even getting subscribed...

How can I have an Observable<VeggieSummary[]> with rxjs operators?

note: My app's angular version does not support pipe. The RxJS version is v5

CodePudding user response:

Could you try change flatmap to forkjoin to see if it fixes the issue? I think currently it is returning Observable<VeggieSummary>[]

getTransactionDetails(1)
.forkJoin(transactionDetails=>
    transactionDetails.veggiesList
       .map(veggie=>getVeggieSummary(veggie.id)))
.subscribe(result=>
    console.log(result)
)

CodePudding user response:

You just need to wrap the inner observable with forkJoin, this converts the Observable<VeggieSummary>[] to Observable<VeggieSummary[]>

    getTransactionDetails(1)
      .flatMap((transactionDetails) =>
        forkJoin(
          transactionDetails.veggiesList.map((veggie) =>
            getVeggieSummary(veggie.id)
          )
        )
      )
      .subscribe((result) => console.log(result));
  • Related