首页 > 解决方案 > 处理两个 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,
    });
  }

我尝试使用switchMapmergeMap

运营商,但我得到

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 请求而不使用管道另一个运算符,但我想试一试并在服务中进行。任何想法为什么它不起作用?

标签: angularrxjsrxjs-observablesswitchmapmergemap

解决方案


因此,如果我理解正确,您正在尝试获取一些数据(通知),在数据返回时发出发布请求,然后在组件中显示数据。

您遇到的问题是您没有设法从服务发出发布请求并将数据获取到组件。

问题

我看到的问题在这里:

 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 请求)。


推荐阅读