如何使用 RxJS、Axios 和 TypeScript 从 API 调用中 return 对象?

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

我正在拨打 API 电话以获取员工的详细信息并使用 RxJS 和 TypeScript。我想将它们作为键值对存储在 Map 中,如下所示:

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);

但最后,它返回了一张空地图。有什么问题?

要将 Promise<T> 转换为 Observable<T>,您需要使用 RxJS

中的 deferfrom 实用函数
import { defer, from } from 'rxjs';

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

这是使用 JavaScript 的 API 的

的示例
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;
}