Loop array and return data for each id in Observable

两盒软妹~` 提交于 2019-12-03 08:57:56

This is quite possible using nested mergeMap and map. A key approach to stick with Observable is expanding the contacts array into an observable using from function. Then you collect the data using toArray operator. Providing documented example:

public getCombinedData(): Observable<any> {
    return this.getMultipleRelationData()
      .pipe(
        mergeMap((result: any) => 

          // `from` emits each contact separately 
          from(result.contact).pipe(
            // load each contact
            mergeMap(
              contact => this.getSignleData(contact._id),
              // in result selector, connect fetched detail data
              (original, detail) => ({...original, relationship: detail})
            ),
            // collect all contacts into an array
            toArray(),
            // add the newly fetched data to original result
            map(contact => ({ ...result, contact})),
          )
        ),
    );
}

Although kvetis's answer can work for you here is what I implemented, just posting it because I found it interesting to solve.

  public getCombinedData(): Observable<any> {
    return this.getMultipleRelationData()
      .pipe(
        mergeMap((result: any) => {
          let allIds = result.contact.map(id => this.getSingleData(id._id));
          return forkJoin(...allIds).pipe(
            map((idDataArray) => {
              result.contact.forEach((eachContact, index) => {
                eachContact.relationship = idDataArray[index];
              })
              return result;
            })
          )
        })
      );
  }

Here is an example solution for your question, I have made dummy Observables. https://stackblitz.com/edit/angular-tonn5q?file=src%2Fapp%2Fapi-calls.service.ts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!