If you want to make the HttpService
use a promise instead of on RxJS Observable you can use lastValueFrom
wrapping around the this.httpService.post()
call. This will transform the Observable into a promise and you can await
it as normal. Otherwise, if you just return the observable, Nest will handle waiting for the response for you. Either way, you'll need to make sure to use that map((resp) => resp.data)
function you have so you don't end up with circular data in the response object (as Axios's response object is circular by design).
If you're trying to console.log()
the data, you'll want to use tap
along with map
in the form of
this.httpService.post(url, data, options).pipe(
tap((resp) => console.log(resp)),
map((resp) => resp.data),
tap((data) => console.log(data)),
);
tap
is essentially a spy method to tap into the observable, look at the data, and let it pass through. It can mutate the data, but generally it's a good idea to leave that to map
or other rxjs operators.
For just the simple await
ability, something like this is all that's needed
const data = await lastValueFrom(
this.httpService.post(url, data, options).pipe(
map(resp => res.data)
)
);
Example with AxiosRequestConfig
object type (TypeScript)
const requestConfig: AxiosRequestConfig = {
headers: {
'Content-Type': 'YOUR_CONTENT_TYPE_HEADER',
},
params: {
param1: 'YOUR_VALUE_HERE'
},
};
const responseData = await lastValueFrom(
this.httpService.post(requestUrl, null, requestConfig).pipe(
map((response) => {
return response.data;
}),
),
);