简体   繁体   中英

How to return object from API call using RxJS, Axios and TypeScript?

I'm making an API call to get the employee's details and using RxJS and TypeScript. I wanted to store them in a Map as key and value pairs like below:

function getEmps() {
  const empMap = new Map();

  rx
  .from(axios.get(api_url))
  .pipe(
   catchError((err) => {
          logger.error('Error in making api call', {
            error: err
          });

          throw new Error('Error in making api call');
        })
      )
   )
  .pipe(
    map((emps)=>{
      .....
      emps.forEach((empObj) =>{
         empMap.set(id, empObj);
      })
    })
  );
  return empMap;
}
console.log(getMap);

But finally, it's returning an empty map. What is the problem?

To transform a Promise<T> into an Observable<T> you need to use the defer and from utility functions from RxJS

import { defer, from } from 'rxjs';

function getSomething() {
  return defer(() => from(axios.get(...)))
}

Here's an example with using JavaScript's API's

import { defer, from } from 'rxjs';

async function getSomething(): Promise<Map> {
  const emps = await axios.get(...)
  const empMap = new Map();
  emps.forEach((empObj) => empMap.set(empObj.id, empObj))
  return empMap;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM