【问题标题】:How share data, which I get with subscribe in component, between components如何在组件之间共享通过订阅组件获得的数据
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!是的,数据使用ngFor显示在子模板中,但我不在子组件中使用它进行操作,所以它是未定义的
    • 如果您想在订阅的同一个组件中使用,请使用变量“data”,例如在 app-root 中写入 {{data}}。如果您想订阅一个组件并在另一个组件中显示,您可以查看stackoverflow.com/questions/50076225/…
    猜你喜欢
    • 2017-08-27
    • 2020-08-31
    • 2020-10-04
    • 2021-10-12
    • 2021-09-16
    • 1970-01-01
    • 2020-11-08
    相关资源
    最近更新 更多