【发布时间】:2022-01-19 12:59:35
【问题描述】:
Nestjs suggests 使用从 @nestjs/axios 导入的 HttpModule 来执行对外部 API 的请求。
我了解HttpService 将响应转换为Observables。
目标
从外部 API 请求数据并在应用程序内部使用数据。
问题
我不明白如何从请求中实际检索数据。我在其他一些答案中读到,如果您从 Controller 返回 observable,Nestjs 会自动为您处理它并将数据返回给客户端。这很好,但是,我没有在 Controller 中使用它。我需要数据在应用程序中可用。
我有一个服务:
@Injectable()
export class ExampleService {
// constructor
getData(): Observable<AxiosResponse<any[]>> {
return this.httpService.get(`http://some-url.com`);
}
}
如何在应用程序逻辑中使用getData() 来获取Observable 返回的数据?在这种情况下,使用带有Promises 的普通axios 请求而不使用HttpModule 会更好吗?
目前我发现的唯一解决方案是使用subscribe:
this.httpService.get(`http://some-url.com`)
.subscribe((value) => {
console.log(value);
});
与所有花哨的async ... awaits相比,这似乎最终会陷入回调地狱。
【问题讨论】:
-
您可以拨打
getData订阅。this.service.getData().subscribe -
这与调用
httpService.get().subscribe相同,我已将其包含在我的问题中。