angular - 如何检测通过 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 中使用它。
所以我的问题来了:有没有办法让第二个组件在第一个组件中的日期发生变化时得到通知,以便立即显示它?
谢谢你。
解决方案
将以下行移动到 ngOnInit()
this.eventService.data$.subscribe(data => this.selectedDay = data);
推荐阅读
- git - 知道为什么我会收到此 git 错误:1622754048270
- c++ - 在 SFML 中检测窗口边界冲突的问题
- javascript - 反应不更新窗口间隔中的状态变量
- javascript - React-网络摄像头录制、回放、重新录制、存储
- r - 在 R 中使用 tidyverse 重新调整因子和重新排序因子
- tensorflow - google colab 您的会话因未知原因而崩溃 .convert()
- intellij-idea - 在 intellij filewatchers 中使用 sass 编译 scss 时出错
- javascript - 如何循环应用 div 类的 span id?
- environment - 在 mac 中查找 conda env 文件夹
- java - RejectedAccessException:没有找到这样的构造函数