如何在组件之间共享我在组件中订阅获得的数据

How share data, which I get with subscribe in component, between components

在我的组件中,我使用 .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 显示它,但它不适用于组件中的这些数据,但我需要这样做。

谢谢!

@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
  }