问题描述
这是我的第一个 Angular 项目,我对 Observables 和 RxJS 仍然不太熟悉。 在我的项目中,起初我想通过 get 请求获取所有通知。之后,我想获取最后一个通知的 id,这样我就可以向服务器发送 post 请求以将它们全部标记为已读。 所以服务中的代码是这样的:
getNotifications(limit: number,page: number): any {
return this.http
.get<INotifications>(
`${API_URL}/notifications?direction=desc&limit=${limit}&order_by=created_at&page=${page}`
)
.pipe(
switchMap((response) => {
const id = response.data[0].id;
return this.markNotificationsAsRead(id);
})
);
}
markNotificationsAsRead(id: number) {
return this.http.post(`${API_URL}/notifications/${id}/mark_all_as_read`,{
id,});
}
我尝试了 switchMap 和 mergeMap
运营商,但我明白
RangeError: 无效的数组长度
组件中的代码:
fetchData() {
this.notificationsService.getNotifications(this.limit,this.Meta?.next_page || 1).subscribe(
(response) => {
this.notifications = [...this.notifications,...response.data];
this.Meta = response.Meta;
this.isLoading = false;
// const mostRecentNotification = response.data[0].id;
// this.markNotificationsAsRead(mostRecentNotification);
},(error) => {
this.handleErrors(error);
}
);
}
顺便说一句:我可以通过删除 fetchData 函数中的这个注释部分来使它工作,并且只返回 get 请求而不用管道另一个操作符,但我想尝试一下并在服务中执行它。 任何想法为什么它不起作用?
解决方法
所以如果我理解正确的话,您正在尝试获取一些数据(通知),在数据返回时发出 post 请求,然后在您的组件中显示数据。
您遇到的问题是您没有设法从服务发出发布请求并将数据发送到组件。
问题
我看到的问题在这里:
switchMap((response) => {
const id = response.data[0].id;
return this.markNotificationsAsRead(id);
})
这样做是将 markNotificationsAsRead()
的值返回给您的 subscribe
,而不是您期望的通知数据。
解决办法
您使用 switchMap()
将两个请求合二为一是正确的。我相信您只需要一个小的修改:
switchMap((response) => {
const id = response.data[0].id;
return this.markNotificationsAsRead(id).pipe(map(() => response));
})
通过添加 pipe(map(() => response))
,您将返回第一个 observable 的值,同时仍然订阅第二个(从而发出发布请求)。