2

我正在尝试使用 Angular 材质分页器和排序,并从 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);
}

当服务器返回错误并 catchError 处理它时,排序 ang paging stopt 以向服务器发送请求。他们的例子有什么问题?

4

2 回答 2

3

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

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)
于 2018-11-27T16:48:34.283 回答
1

或者,您可以从 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([]);
    })
  );
}),
于 2018-11-27T20:36:20.937 回答