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

Typescript 从Nestjs中可观察到的响应中返回数据,typescript,observable,nestjs,Typescript,Observable,Nestjs,我不熟悉打字脚本,基本上是后端开发。我正在开发一个简单的天气应用程序,从中获取天气数据。 我正在使用嵌套内置的HttpModule,它将Axios包装在其中,然后使用HttpService发出打开天气的GET请求。请求返回一个可观察到的,对我来说完全是新闻。 如何从可注入服务中的可观察对象中提取实际响应数据,并将其返回给控制器 这是我的天气预报 import { Injectable, HttpService } from '@nestjs/common'; @Injectable() exp

我不熟悉打字脚本,基本上是后端开发。我正在开发一个简单的天气应用程序,从中获取天气数据。 我正在使用嵌套内置的
HttpModule
,它将Axios包装在其中,然后使用
HttpService
发出打开天气的GET请求。请求返回一个可观察到的,对我来说完全是新闻。 如何从
可注入服务
中的可观察对象中提取实际响应数据,并将其返回给
控制器

这是我的天气预报

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;
  }
}
还有人能澄清一下我的代码中缺少的类型吗?

基本上是高级回调。因为它们是以异步方式工作的,所以您需要让您的代码来处理这个问题。Nest可以处理从控制器返回的可观察对象,并将在后台为您订阅它,因此您在服务中需要做的事情如下:

从'@nestjs/common'导入{Injectable,HttpService};
@可注射()
导出类应用程序服务{
构造函数(私有httpService:httpService){}
getWeather(){
返回此.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a)。烟斗(
映射(response=>response.data)
);
}
}
map
是从
rxjs/operators
导入的,它类似于
Array.prototype.map
,因为它可以接收值并根据需要进行转换。从这里开始,您的
控制器
只需要返回
this.appService.getWeather()
,其余的由Nest处理


另一个选择是使用
.toPromise()
将可观测值转换为承诺,然后可以使用通常的
async/await
语法,这是另一个有效的选择。

谢谢,我已经解决了这个问题,并将其转换为
toPromise()
,这使得使用async/await更容易