angularrxjsxrm

Observable from a Promise with nested Promise


I have a service that call the new Xrm.WebApi endpoint.

This endpoint return a Promise, which have a nested Promise "json" (documentation), which allows to get the json returned by the service.

From this json I extract some data using the "parseData" method, which return it as an Array of objects.

I want to return an Observable<MyObject[]>, but all I can get for now is an Observable<Promise<MyObject[]>>.

My current code looks like the following :

return from(Xrm.WebApi.online.execute(crmRequest).then(
      result => {
        if (result.ok) {
          return result.json().then(json => {
            let res : MyObject[]= this.parseData(json);
            return res;
          }); 
        }
      },
      error => {
        throw error;
      }
    ));

Environment:
- Angular 8.2
- RxJs 6.4


Solution

  • Use from to convert your first Promise to an Observable and use switchMap to map to an inner Promise. filter is used to only emit results that are ok and map is used to map to your desired output. This Observable will error when the first or second Promise errored.

    return from(Xrm.WebApi.online.execute(crmRequest)).pipe(
      filter(result => result.ok),
      switchMap(result => result.json()),
      map(json => this.parseData(json) as MyObject[]),
    )
    

    For more info read my response at: Convert Promise to Observable