Stop Angular http Observable 流因错误而关闭

Stop Angular http Observable stream closing on error

我有一个主题 (this.searchSubject),当我想执行搜索时我会调用它的 next():

this.searchSubject.next(postBody)

这会导致以下事件发生:

this.searchSubject
      .switchMap((view: any) => {
         // upsert here records the search - needed
         return this.searchHistoryService.upsert(view)
          .flatMap(() => this.http.post(this.url, view))
          .map((data) => this.pageTransform(data));
      })
      .subscribe(res => {
        this.successSubject.next(this.pageTransform(res));
      }, err => {
        this.errorSub.next(err);
      });

不幸的是,无论我做什么,如果 this.errorSub.next(err); 被调用(错误情况),我似乎都无法让流保持活动状态。

自从 httpClient (this.http.post) returns 一个新的 observable each 我不认为处理错误会是一个问题,但似乎这从 this.searchSubject 中删除了所有观察者。

注意我有一个 httpInterceptor,它 returns 为每个返回的错误抛出一个错误。

这一定是一个非常常见的模式,所以我做错了什么?

您的错误处理程序位于外部 switchMap 投影中,因此它会在发生错误时关闭外部流。您必须将它移到您的 switchMap 内部以保持外部流活动。

并且由于您使用的是 rxjs@5.5.2,因此您可以使用可出租运算符,这样可以更轻松地查看错误处理程序的放置位置。

this.searchSubject.pipe(
  switchMap((view: any) => {
   return this.searchHistoryService.upsert(view)
    .pipe(
      flatMap(() => this.http.post(this.url, view)),
      map((data) => this.pageTransform(data)),
      catchError(() => {
        this.errorSub.next(err); 
      })
    );
  })
).subscribe(() => {
  this.successSubject.next(this.pageTransform(res));
});

如果您切换到可出租运算符,一个重要的注意事项是您必须从 rxjs/operators 导入它们,例如 import { map, catchError } from 'rxjs/operators';

如果您继续使用旧语法,我认为在 .map() 投影后添加 .catch 会很简单。