我无法正确共享我的 Observable 流并且我的 http 请求调用了两次

I cannot share my Observable stream properly and my http request calls twice

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

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));

要使 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));