首页 > 解决方案 > 我无法正确共享我的 Observable 流并且我的 http 请求调用了两次

问题描述

嘿,我对共享运营商有疑问。当我使用带有 data$ 和 totalElements$ 的异步管道时,我的 http 请求执行了两次。我希望它只执行一次。我尝试使用 shareReplay ,但效果不佳。

filters$: BehaviorSubject<any> = ...
...

getComplaints() {
  return this.filters$.pipe(
    flatMap(filters => {
      this.loading = true;
      return this.complaintService
        .getComplaints$(filters)
        .pipe(
          finalize(() => this.loading = false),
          share()
        );
      })
    );
 }

this.data$ = this.getComplaints().pipe(map(value => value.pageItems));
this.totalElements$ = this.getComplaints().pipe(map(value => value.totalItems));

标签: angulartypescriptrxjsreactive-programming

解决方案


为了share工作,您必须只创建一个可观察对象(所以不要使用函数)并将运算符放在外部可观察对象上。您可能希望使用shareReplay以便迟到的订阅者获得最新的价值。

this.complaints$ = this.filters$.pipe(
  flatMap(filters => {
    this.loading = true;
    return this.complaintService
      .getComplaints$(filters)
      .pipe(
        finalize(() => this.loading = false),
      );
    }),
  shareReplay(1)
);

this.data$ = this.complaints$.pipe(map(value => value.pageItems));
this.totalElements$ = this.complaints$.pipe(map(value => value.totalItems));

推荐阅读