只要订阅发生错误,计时器就会停止

Timer stops whenever an error occurred in the subscription

我有一个服务,运行 在其构造函数中有一个计时器。 计时器调用一个异步函数,该函数调用一个 API 并且应该 return 一个 Observable。 一切正常时 运行ning 就好了。 我正在尝试在 API 关闭时实施错误处理。 问题是每当发生错误时,计时器就会停止执行。

查看我的代码:

subscription : Subscription;
constructor(private httpClient : HttpClient)
{
    this.subscription = timer(0, 10000).pipe
    (
        switchMap(() => this.getData();
    }).subscribe();
}


getData(): Observable<someModel>
{
    return this.httpClient.get<someModel>(<url>)
    .pipe(
    tap(response => 
    {
        do something 
    }),
    catchError(error =>
    {
        <doSomeErrorHandling>
        return throwError(error);
    })
    );
}

发生错误时关闭可观察对象。因此,您可以使用 of function. If you're worried it might tangle up the actual response handling mechanism, you could using RxJS NEVER 常量将其转换为 next 通知,而不是使用 throwError 函数转发错误,从而不会从 catchError 块发出任何内容。

尝试以下方法

import { of, NEVER } from 'rxjs';
getData(): Observable<someModel>{
  return this.httpClient.get<someModel>(<url>).pipe(
    tap(response => {
      do something
    }),
    catchError(error => {
      // <doSomeErrorHandling >
      return of(error); // (or) return NEVER;
    })
  );
}

也尽量使用 tap 只是为了副作用。在您只有一个 switchMap 的情况下,您可以处理订阅内的通知。

switchMap 如果它的任何内部可观察对象 [this.getData(),在本例中] 出现错误,则会发出错误。相反,您可能想要捕获内部可观察对象本身的错误。

还请记住,RxJS 流会发出一次 error 一次 complete 发射。永远不会更多,永远不会两者兼而有之。如果错误到达您的 switchMap,则您的流的该部分将永远完成。相反,您可以使用重试从头开始重新创建流。

subscription : Subscription;
constructor(private httpClient : HttpClient){
  this.subscription = timer(0, 10000).pipe(
    switchMap(_ => this.getData().pipe(
      catchError(err => /*Do something*/)
    )
  ).subscribe();
}