【问题标题】:Return data from response within an observable in Nestjs从 Nestjs 中的 observable 中的响应返回数据
【发布时间】:2021-03-22 03:03:36
【问题描述】:

我是 Nestjs、Typescript 和基本上后端开发的新手。我正在开发一个简单的天气应用程序,我从Open Weather API 获取天气数据。 我正在使用 Nest 内置的 HttpModule 将 Axios 包装在其中,然后使用 HttpService 发出 GET 请求以打开天气。该请求返回一个 Observable,这对我来说完全是新闻。 如何从 Injectable service 中的 observable 中提取实际响应数据并将其返回给 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;
  }
}

这是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;
  }
}

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

【问题讨论】:

    标签: typescript observable nestjs


    【解决方案1】:

    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 语法,这是另一个有效的选择。

    【讨论】:

    • 谢谢,我已经想通了,并确实转换了toPromise(),这使得使用 async/await 变得更容易
    猜你喜欢
    • 2022-07-20
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2018-07-20
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多