Reputation: 40946
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
).
I'd like the application to make a 2nd request, make a 3rd request, then throw the error to be caught by this.handleError()
What actually happens: application makes a 2nd request, makes a 3rd, then Observable completes without error ("Complete" printed to console)
Angular 2 rc.6
, RxJS 5 beta 11
, Typescript 2.0.2
Upvotes: 2
Views: 2297
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 executionsource
: 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