【发布时间】:2021-10-13 17:37:24
【问题描述】:
我对 Angular 还很陌生,我试图从 Http 响应对象中只获取某些值。
在我的服务中,我正在执行获取请求以获取给定城市的天气数据,如下所示:
export class CityService {
private baseUrl = 'https://api.openweathermap.org';
constructor(private http: HttpClient) { }
getCity(name: string){
return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`);
}
}
现在,在组件中,我正在注销响应,如下所示:
ngOnInit(): void {
this.cityService.getCity('lucija').subscribe(data => {
console.log(data)
});
}
响应本身只是一个包含许多字段(也是嵌套字段)的对象,其中大多数我不需要。
我还设置了一个界面,我想在这些特定响应字段中“保存”:
export interface City {
name: string;
description: string;
icon: string;
main: object;
search: string;
}
我该怎么做?干杯!
编辑: 根据下面的答案,我得到了 2 个错误,我这样解决了:
getCity(name: string): Observable<City>{
return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`)
.pipe(map((res: any) => <City>{
name: res.name,
description: res.weather[0].description,
icon: `http://openweathermap.org/img/w/${res.weather[0].icon}.png`,
main: res.main,
search: name
}));
【问题讨论】:
标签: javascript angular typescript