我想我快疯了,因为我对 node 和 typescript 还很陌生……我只想以同步的方式检索 http get 请求的结果.
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.
给定:
import { Injectable, HttpService } from '@nestjs/common'; import {} from '@nestjs/core'; @Injectable() export class AppService { private readonly DATA_URL:string = "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 } }编辑:我在这里写了完整的代码,因为它可能对其他学习框架的人有用.我用了Jay的回答,但是richbai对我理解背后的理论也有很大帮助.当然,如果它还能变得更好,就改进/纠正.
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 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]}))), ); }
如果您需要从 Nest 服务执行此操作,并将结果返回给客户端,您只需返回可观察对象,Nest 将处理订阅为你从那里.如果您需要进行任何额外的数据处理,您可以在 Observable 的 .pipe() 运算符之后使用 map 运算符.一个例子可能是仅从 axios 响应中获取数据,而不是整个响应(这会导致 JSON.stringify() 出现问题,因为它在本身).
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).
下面是这样的一个例子
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 = 'remote/data.json'; constructor(private readonly http: HttpService) {} callHttp(): Observable<Array<Object>> { return this.http.get(this.DATA_URL).pipe( map((axiosResponse: AxiosResponse) => { retrun axiosResponse.data; }) ); } }从这里开始,如果您有一个调用 this.httpConsumingService.callHttp() 的控制器,Nest 将调用该服务,订阅 observable,并在后台从它返回数据.不需要额外的工作.如果您正在寻找有关 Observables 和可用操作的更多信息,learnrxjs.io 是一个不错的来源.
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.
更多推荐
如何处理 axios httpservice observable 响应?
发布评论