Angular 2 RxJS Observed: Retry after filtering again filter Error condition

I am using Angular 2 HTTP library which returns observable. I want to implement a retry with a specific status / error code.

I have a problem, if the error is not 429, Observable.of(error) is executed in case of an error, to try again, but when all your retries are not executed, the thread goes to the success block instead of the catch block.

How to make thread execution to block a block in all attempts unsuccessful?

  return this.http.get(url,options) .retryWhen((errors) => { return errors .mergeMap((error) => (error.status === 429) ? Observable.throw(error) : Observable.of(error)) .take(2); }) .toPromise() .then((res:Response) => console.log('In Success Block')) .catch((res) => this.handleError(res)); 

he will solve my problem

  return this.http .post(url, JSON.stringify(body), requestOptions).retryWhen((errors) => { return errors .mergeMap((error) => (error.status === 404) ? Observable.throw(error) : Observable.of(error)) .take(2); }).map((res:Response) =>{ if (res.status === 200) return res; else return Observable.throw(res); }) .toPromise(); 
+3
angular typescript observable rxjs5
source share
1 answer

A bit late for the party, but I recently implemented this behavior. Here is my solution:

  post<T>(serviceUrl: string, data: any): Observable<T> { return Observable.defer(() => { return super.post<T>(serviceUrl, data); }).retryWhen((error) => { return this.refresh(error); }); } 

And update function:

 refresh(obs: Observable<any>): Observable<any> { return obs .switchMap((x: any) => { if (x.status === 401) { return Observable.of(x); } return Observable.throw(x); }) .scan((acc, value) => { return acc + 1; }, 0) .takeWhile(acc => acc < 3) .flatMap(() => { console.log('Token refresh retry'); return this.tokenRefreshService.refreshToken(); }); } 

A use case is that whenever I make an HTTP request and get a 401 response, I want to update the token and then repeat the initial request with a new token. When 401 happens, I use switchMap to return a new Observable, otherwise I return Observable.throw (x), which stops the execution of the retry logic.

And the calling code looks like this (where the error is called whenever you return Observable.throw (x)):

  this.http.post(x).subscribe(response => { ... } }, error => { ... } }); 
+8
source share

All Articles