我正在创建我的第一个 Angular 应用程序,但我正在努力解决可观察的问题(惊喜、惊喜)。我的 HTML 标签中有这个:
<mwl-calendar-month-view
*ngSwitchCase="'month'"
[viewDate]="viewDate"
[events]="observable | async"
[activeDayIsOpen]="true"
>
我尝试将异步管道与我的 observable 一起使用。为了更新我的 observable 的值,我进行了一些 REST 调用(在用户单击按钮后),这是我处理单击的方式:
observable: Observable<CalendarEvent[]>;
behaviourSubject: BehaviorSubject<CalendarEvent[]> = new BehaviorSubject([{
title: 'title12345',
start: new Date(),
end: new Date()
}]);
(...)
onCreateCalendarEventClick() {
let calendarEvent: CalendarEvent;
calendarEvent = {
title: (document.getElementById('calendarEventName') as HTMLInputElement).value,
start: new Date((document.getElementById('calendarEventStartDate') as HTMLInputElement).value),
end: new Date((document.getElementById('calendarEventEndDate') as HTMLInputElement).value),
color: undefined
};
let calendarEventApi: CalendarEventApi;
let calendarEventColor;
if (calendarEvent.color) {
calendarEventColor = calendarEvent.color;
}
calendarEventApi = {
title: calendarEvent.title,
start: ToApiMapper.formatDateTimeToApi(calendarEvent.start),
end: ToApiMapper.formatDateTimeToApi(calendarEvent.end),
color: ToApiMapper.mapColorToApi(calendarEventColor)
};
this.calendarService.saveCalendarEvent(calendarEventApi).subscribe( () => {
this.fetchCalendarData();
}, error => {
this.alertService.displayAlert('saving calendar event failed: ' + error);
});
}
private fetchCalendarData() {
const calendarEvents: CalendarEvent[] = [];
this.calendarService.fetchCalendarData(this.userService.getLoggedUser()).subscribe(calendarEventsApi => {
calendarEventsApi.forEach(calendarEventApi => {
const calendarEvent: CalendarEvent = {
title: calendarEventApi.title,
start: new Date(calendarEventApi.startDate),
end: new Date(calendarEventApi.endDate),
color: {
primary: calendarEventApi.eventColour,
secondary: calendarEventApi.eventColour
}
};
calendarEvents.push(calendarEvent);
});
this.behaviourSubject.next(calendarEvents);
this.observable = this.behaviourSubject.asObservable();
});
}
我试图重现此处描述的行为:https://malcoded.com/posts/angular-async-pipe/ 我如何理解我的代码中发生的事情:从 REST 调用获取响应正文后,我更新了下一个值,其 behaviorSubject 将具有. 然后我创建一个新的 observable,下一个值已经设置为我想要的响应。然后我用 HTML 更新我的 observable。应该重新加载 HTML(因为它会监听值的变化和我的 observable 的值刚刚改变)。我的 REST 调用中的新值应该在 HTML 中可见。我错过了什么?