catchError 后合并管道死亡

merge pipe die after catchError

我正在尝试使用 Angular material 分页器和排序,并从 material.angular.io 示例中获取一些代码。这部分:

ngOnInit() {
    this.exampleDatabase = new ExampleHttpDao(this.http);

    // If the user changes the sort order, reset back to the first page.
    this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);

    merge(this.sort.sortChange, this.paginator.page)
      .pipe(
        startWith({}),
        switchMap(() => {
          this.isLoadingResults = true;
          return this.exampleDatabase!.getRepoIssues(
            this.sort.active, this.sort.direction, this.paginator.pageIndex);
        }),
        map(data => {
          // Flip flag to show that loading has finished.
          this.isLoadingResults = false;
          this.isRateLimitReached = false;
          this.resultsLength = data.total_count;

          return data.items;
        }),
        catchError(() => {
          this.isLoadingResults = false;
          // Catch if the GitHub API has reached its rate limit. Return empty data.
          this.isRateLimitReached = true;
          return observableOf([]);
        })
      ).subscribe(data => this.data = data);
}

当服务器return发生错误并且catchError 处理它时,排序和分页停止向服务器发送请求。他们的例子有什么问题?

这就是 observable 的工作方式,在 onComplete 或 onError 的情况下,observable 将停止。如果你想让它恢复,你可以在 catchError 之后添加一个 repeat 运算符,你的源 observable 是一个热 Observalbe,所以你不必担心自动无限循环。或者,您可以查看 repeatWhen operator

merge(this.sort.sortChange, this.paginator.page)
  .pipe(
    startWith({}),
    switchMap(() => {
      this.isLoadingResults = true;
      return this.exampleDatabase!.getRepoIssues(
        this.sort.active, this.sort.direction, 
        this.paginator.pageIndex).pipe(
          map(data => {
             // Flip flag to show that loading has finished.
             this.isLoadingResults = false;
             this.isRateLimitReached = false;
             this.resultsLength = data.total_count;
             return data.items;
         }),
          catchError(() => {
             this.isLoadingResults = false;
             this.isRateLimitReached = true;
             return observableOf([]);
          })
        );
    })
  ).subscribe(data => this.data = data)

或者,您可以从 switchMap 中捕获错误,这不应该终止合并。

switchMap(() => {
  this.isLoadingResults = true;
  return this.exampleDatabase!.getRepoIssues(
    this.sort.active, this.sort.direction, this.paginator.pageIndex).pipe(
    catchError(() => {
      this.isLoadingResults = false;
      this.isRateLimitReached = true;
      return observableOf([]);
    })
  );
}),