返回Nestjs中可观察到的响应中的数据



我对Nestjs、Typescript和基本上后端开发都是新手。我正在开发一个简单的天气应用程序,从开放天气API获取天气数据。我使用Nest内置的HttpModule,它将Axios封装在其中,然后使用HttpService向Open weather发出GET请求。请求返回一个Observable,这对我来说完全是个新闻。如何从Injectable service中的可观测数据中提取实际响应数据并将其返回给Controller

这是我的天气预报服务

import { Injectable, HttpService } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(private httpService: HttpService) {}
getWeather() {
let obs = this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a');

console.log('just before subscribe');

obs.subscribe((x) => {
let {weather} = x.data;
console.log(weather);
})
console.log('After subscribe');

// TODO: Should extract and return response data f
// return;
}
}

这是weather.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getWeather() {
const res = this.appService.getWeather();
return res;
}
}

还有人能澄清我的代码中缺少的类型是什么吗?

RxJS Observables本质上是高级回调。因为它们是以异步方式工作的,所以您需要让代码来处理它。Nest可以处理从控制器返回的Observable,并将在后台为您订阅它,所以您在服务中所需要做的就是这样:

import { Injectable, HttpService } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(private httpService: HttpService) {}
getWeather() {
return this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a').pipe(
map(response => response.data)
);

}
}

map是从rxjs/operators导入的,与Array.prototype.map相似之处在于,它可以接受中的值并根据需要对其进行转换。从这里开始,您的Controller只需要返回this.appService.getWeather(),Nest将处理其余部分。

另一种选择是使用.toPromise()将observable转换为promise,然后可以使用常用的async/await语法,这是另一种有效的选择。


RxJS v7和

RxJS v7中已弃用toPromise()。现在建议使用lastValueFrom(observable)firstValueFrom(observable)来生成可观察的异步。

尝试通过将observable转换为promise来返回值。

getProductList(({return firstValueFrom(this.workflowService.getProductList(((.then(res=>{return res.data}(;}

最新更新