【发布时间】: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