Angular + RxJS: repeat the request on status code 202

Viewed 3776

I have a simple request that I would like to repeat in case the response is with status 202. Currently, it looks like this:

this.http.get(endPoint, {
    withCredentials: true,
    headers: this.headers
})
.map((response: Response) => {
    return response.text() ? response.json() : '';
})
.catch((error) => this.handleError(error));

I have tried with .repeatWhen() but unfortunately, I don't receive the Response object and I cannot set a validation by the status code.

Any ideas how can I do that?

4 Answers

Use this for Rx 6. This retries the 202 up to 3 times, and throws a timeout error at the end of the third try.

@Injectable()
export class ProgressInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(
            map(t => {
                if (t['status'] === 202) {
                    throw 202;
                }
                return t;
            }),
            retryWhen(t => {
                return t.pipe(
                    concatMap((e, i) => {
                        if (e !== 202) {
                            return throwError(e);
                        }
                        return iif(
                            () => i >= 2,
                            throwError(new Error('Operation Timed Out!')),
                            of(e).pipe(delay(1000))
                        )
                    })
                )
            }),
        );    
    }
}
Related