Search code examples
angulartypescriptrxjs

Angular/RxJS: keep interval running even in case of an error


I need to call a REST-service every 10 seconds. The REST-client call is inside an angular-service (myservice, function foo).

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

That is working as long the connection to the REST-service is ok. But if I stop it, then the interval stops too.

What do I need to do to keep it running (and failing) even if the REST-service is off?


Solution

  • How about cathing the error on the "inner" observable (the one that may actually produce errors), not the whole stream? Something like:

    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);
    }