Angular / RxJS:即使出现错误,也要保持间隔运行

时间:2018-08-10 18:31:37

标签: angular typescript rxjs

我需要每10秒调用一次REST服务。 REST客户端调用在angular-service(myservice,函数foo)内部。

 ngOnInit ()
 {
      interval (10000).pipe (startWith (0), mergeMap (obs =>
      this.myservice.foo ())).subscribe (resp =>
      {
        this.data = resp;
      },
      error =>
      {
        console.log ("error");
      }
      );
 }

只要与REST服务的连接正常就可以。但是,如果我停止它,那么间隔也会停止。

即使REST服务已关闭,我该怎么办才能使其运行(并发生故障)?

4 个答案:

答案 0 :(得分:2)

这不是针对特定情况的特定答案(我希望在尝试发布建议的代码之前先进行一次堆栈闪电试验来尝试一下)。但是,这是一段视频的屏幕截图,讨论了与Ward Bell隔离错误的问题。

enter image description here

请注意两段代码上方的“错误方式”和“正确方式”注释。

您可以在此处找到演讲的这一部分:https://www.youtube.com/watch?v=q--U25yPTrA&feature=youtu.be&t=1240

答案 1 :(得分:2)

如何在“内部”可观察到的错误(实际上可能产生错误的错误)上处理错误,而不是整个流程?像这样:

ngOnInit () {
  interval(10000).pipe(
    startWith(0),
    mergeMap(obs => this.myservice.foo().pipe(
      catchError((error) => {
        console.log(error);
        return empty(); // or return of(error) and do sth about it in the subscribe body
      }),
    ),
  )).subscribe(resp => this.data = resp);
}

答案 2 :(得分:1)

FlatMap的值是内部可观察值,用于处理错误。在内部可观察对象上,向catchError可观察对象静默处理错误的管道上添加empty处理程序。示例:

interval(10000).pipe(
  flatMap(num => of(num).pipe(
    mergeMap(num => this.myservice.foo()),
    catchError((error) => {
      console.log ("error");
      return empty();
    })
  ))
).subscribe(resp => {
  console.log(resp)
});

Stackblitz

答案 3 :(得分:1)

您可以使用retyWhen错误运算符

interval (10000)
  .pipe(
    startWith(0),
    switchMap (obs => this.myservice.foo()),
    retryWhen(error => {
      return error.flatMap((error: any) => {
          if(error.status  === 503) {
              return Observable.of(true);
          }
          return Observable.throw({error: 'No retry'});
      });
);