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?
CodePudding user response:
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;
}