Issue
I think I'm getting crazy as I'm pretty new to node and typescript...I simply want to retrieve, in a syncronous way, the result of an http get request.
Given:
import { Injectable, HttpService } from '@nestjs/common';
import {} from '@nestjs/core';
@Injectable()
export class AppService {
private readonly DATA_URL:string = "https://remote/data.json";
constructor(private httpService:HttpService){}
getSomething(): Array<Object> {
let resp = this.httpService.get(this.DATA_URL); //what do I do now?? It's an observable
}
}
edit: I'm writing here the full code as it could be useful to others learning the framework. I used Jay's response, but richbai also helped me a lot in understanding the theory behind. Of course improve/correct if it can still get better.
- I added a type to have better control instead of Object
- I needed to change the date field from the response from "yyyy-mm-ddThh24:mi:ss" to "yyyy-mm-dd"
I also needed to filter the response based on a value
getSomething(aFilterValue:number): Observable<RespDTO[]> { return this.httpService.get(this.DATA_URL).pipe( map((axiosResponse : AxiosResponse) => (axiosResponse.data as RespDTO[]) .filter((el:RespDTO) => el.aCode===aFilterValue) .map((el:RespDTO) => ({...el,aDateField:el.aDateField.split('T')[0]}))), ); }
Solution
If you are needing to do this from a Nest service, and return the result back to the client, you can simply return the observable and Nest will handle the subscription for you from there. If you need to do any extra data processing you can use the map
operator after the .pipe()
operator of an Observable
. An example of this could be getting only the data from the axios response and not the entire response (which would have trouble with JSON.stringify()
because it has circular references on itself).
The following is an example of such
import { Injectable, HttpService } from '@nesjts/common';
import { AxiosResponse } from 'axios';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class HttpConsumingService {
private readonly DATA_URL = 'http://remote/data.json';
constructor(private readonly http: HttpService) {}
callHttp(): Observable<Array<Object>> {
return this.http.get(this.DATA_URL).pipe(
map((axiosResponse: AxiosResponse) => {
return axiosResponse.data;
})
);
}
}
From here, if you have a controller that calls this.httpConsumingService.callHttp()
, Nest will call the service, subscribe to the observable, and return the data from it under the hood. No extra work needed. If you're looking for more info on Observables and the available operations learnrxjs.io is a pretty good source.
Answered By - Jay McDoniel Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.