首页 > 解决方案 > 如何检测通过 Angular 主题发送的数据?

问题描述

我在 Angular 中有两个组件显示在同一页面上。在第一个中,我要求用户选择一个日期,在第二个中,我想显示该日期的天气预报。

这是我现在拥有的有用代码:

事件服务.ts

data$:Subject<number> = new Subject<number>();

event-update.component.ts(第一个组件)

  sendWeather(): void {
    this.eventService.data$.next(this.editForm.get('startDate')!.value / 1000);
  }

weather-service.component.ts(第二个组件)

export class WeatherServiceComponent implements OnInit {
  weather!: any;
  shweather = false;
  day!: number;
  selectedDay!: number;

  constructor(
    private eventService: EventService
  ) { }

  ngOnInit(): void {
    this.eventService.getWeather().subscribe((res: Object) => (this.weather = res));
  }

  showWeather(): void {
    this.updateWeather()
    this.shweather = !this.shweather;
  }

  updateWeather(): void {
    this.eventService.data$.subscribe(data => this.selectedDay = data);
    this.day = -1;
    for (let i = 0; i <= 7; i++) {
      if (this.selectedDay === this.weather.daily[i]!.dt - 43200) {
        this.day = i;
      }
    }
  }
}

这可以很好地获取第二个组件的日期,但是如果您更改第一个组件中的日期,则第二个组件仅在调用 updateWeather() 方法时才会更新,因为这是我们从事件中的主题获取数据时服务。

当按下按钮时调用 showWeather(),我需要计算变量“day”,因为我在 HTML 中使用它。

所以我的问题来了:有没有办法让第二个组件在第一个组件中的日期发生变化时得到通知,以便立即显示它?

谢谢你。

标签: angulartypescript

解决方案


将以下行移动到 ngOnInit()

this.eventService.data$.subscribe(data => this.selectedDay = data);

推荐阅读