angular - 处理两个 HTTP 请求(Angular + RxJS)
问题描述
这是我的第一个 Angular 项目,我仍然对 Observables 和 RxJS 不太熟悉。在我的项目中,起初我想通过获取请求获取所有通知。之后,我想获取最后一个通知的 id,这样我就可以向服务器发送发布请求以将它们全部标记为已读。所以服务中的代码如下所示:
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 请求而不使用管道另一个运算符,但我想试一试并在服务中进行。任何想法为什么它不起作用?
解决方案
因此,如果我理解正确,您正在尝试获取一些数据(通知),在数据返回时发出发布请求,然后在组件中显示数据。
您遇到的问题是您没有设法从服务发出发布请求并将数据获取到组件。
问题
我看到的问题在这里:
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 的值,同时仍订阅第二个(并因此发出 post 请求)。
推荐阅读
- php - 如何使用 PHP 从两个不同的表中进行选择,从结果中生成变量并对它们进行数学运算
- angular - ng2-fancy-image-uploader 不能在 Angular 8 中工作
- database - 捕获导致 ORA-01438 的列:值大于此列允许的指定精度
- android - adb remount 总是需要 adb root
- c++ - 如何从 CPP 源代码行号中获取 LLVM 位代码行号?
- sql-order-by - 对结果集的行进行排序,但 Redshift 中的一行除外
- r - R函数对数据进行排序
- javascript - 我的解决方案有意义吗?使用 Promise、超时、try/catch
- angular - 如何根据文件类型显示图标并避免 ngIf 条件的数量?
- hosting - 企业互联网和查看 Wix 网站