在我的组件中,我使用.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显示它,但它在组件中的这些数据上并不起作用,但我需要这样做。
谢谢!
答案 0 :(得分:0)
@AndrewGumenniy,Observables是异步的。这意味着,直到它没有完成,你没有数据。但是你不需要关心它。如果您的子组件具有@Input,则当数据更改时,日期将显示在子项中。你只需要一个变量
@Component({
selector: 'app-root',
template: `
<app-child [data]="data"></app-child>
`
})
constructor(private CityWeatherDataService: CityWeatherDataService){}
data:any[]; //<--your variable
daysForecast(city,country){
this.CityWeatherDataService.daysForecast(city,country)
.subscribe(data => {
this.data=data.map(x=>x.humidity); //<--an abreviate way to do your loop
//you needn't return anything
});
}
ngOnInit() {
this.daysForecast("London","UK");
console.log(this.humidity); //<--this give you "null", but that's not important
}