从 Nestjs 中的可观察对象中的响应返回数据

Sei*_* A. 1 observable typescript nestjs

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

这是我的 weather.service.ts

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是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;
  }
}
Run Code Online (Sandbox Code Playgroud)

也有人可以澄清我的代码中缺少哪些类型?

Jay*_*iel 5

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)
    );
   
  }
}
Run Code Online (Sandbox Code Playgroud)

map从进口rxjs/operators和类似Array.prototype.map的,因为它可以在值,并将其转换为必要的。从这里开始,您Controller只需要 return this.appService.getWeather(),Nest 将处理其余的。

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