BeetleJuice
BeetleJuice

Reputation: 40946

RxJS 5 with Angular 2: Retry failed Observable but then forward error

When an HTTP request fails, I'd like to retry twice 1 second apart. If it fails again the third time, I'd like to forward that error to the Observers. I'm having trouble with that last part.

HTTP request from DataService.get()

return this.http.get(url,options)
    .retryWhen(errors => errors.delay(1000).take(2))
    .catch((res)=>this.handleError(res));

Subscription

this.dataSvc.get('/path').subscribe(
    res => console.log(res),
    err => console.error(err),
    () => console.log('Complete')
);

My server is setup to always return an error (status 400 Bad request).

Angular 2 rc.6, RxJS 5 beta 11, Typescript 2.0.2

Upvotes: 2

Views: 2297

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40946

I used the scan operator:

return this.http.get(url,options)
    .retryWhen(errors => errors.delay(1000).scan((acc,source,index)=>{
        if(index) throw source;
    }))
    .catch((res)=>this.handleError(res));

The parameters of scan():

  • acc: an accumulator (think Array.reduce()). If you modify and return it, the new value will be provided as the acc parameter in the next execution
  • source: the value (or exception) emitted by the previous operation (delay(), which itself forwards it from errors)
  • index: Index of the currently emitted value (zero-based)

This makes 3 HTTP requests (Don't know why; I would have expected 2). On the 3rd failure, it throws source -- the error emitted -- to be caught by handleError()

Upvotes: 5

Related Questions