【发布时间】:2018-04-29 10:27:50
【问题描述】:
在我的组件中,我使用 .subscribe
constructor(private CityWeatherDataService: CityWeatherDataService){}
daysForecast(city,country){
this.CityWeatherDataService.daysForecast(city,country)
.subscribe(data => {
for (var i = 0; i < data.length; i++) {
this.humidity.push(data[i].humidity);
}
return data;
});
}
ngOnInit() {
this.daysForecast("London","UK");
console.log(this.humidity);
}
我的服务我确实喜欢这样
daysForecast(city,country): Observable<WeatherItem[]>{
const params = new HttpParams()
.set('city', city)
.set('country', country)
.set('key', '7fddb2fc6bae42a396f121c7bd341832');
return this.http.get('https://api.weatherbit.io/v2.0/forecast/daily', {params})
.map(data=>{
let forecastItemList = data["data"];
return forecastItemList.map(function(forecastItem:any) {
return {
weatherDescription: forecastItem.weather.description,
weatherIcon: forecastItem.weather.icon,
temperature: forecastItem.temp,
humidity: forecastItem.rh,
wind: forecastItem.wind_spd,
cloudiness: forecastItem.clouds,
pressure: forecastItem.pres
};
});
});
}
是否可以不仅在此功能中使用来自 .subscribe 的数据,还可以共享以在另一个组件中使用?现在,当我从 .subscribe 共享数据时,我只能在子组件中使用 ngFor 显示它,但它不适用于组件中的这些数据,但我需要这样做。
谢谢!
【问题讨论】:
标签: json angular observable subscribe