Angular + RxJS: retry request with status code 202

I have a simple request that I would like to repeat in case the response has the status of 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 tried with .repeatWhen(), but, unfortunately, I do not receive the object Response, and I can not set the check by status code.

Any ideas how I can do this?

+5
source share
4 answers

, repeatWhen(). , , , . ( Response).

retryWhen():

this.http.get(endPoint, { withCredentials: true, headers: this.headers })
    .map((response: Response) => {
        if (response.code === 202) {
            throw response;
        }
        return response;
    })
    .map((response: Response) => {
        return response.text() ? response.json() : '';
    })
    .retryWhen(obs => {
        return obs; // always just resubscribe without any further logic
    });

response , retryWhen, . , , , :

.retryWhen(obs => {
   return obs.filter(...);
});
+2

Rx 6. 202 3 - .

@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))
                        )
                    })
                )
            }),
        );    
    }
}
+1

http- catch

.catch(res => {
    return res.status === 202?
        this.http.get(endPoint):
        Observable.throw(res);
});
0

flatMap:

.flatMap((response:Response) => {
    if (response.status === 200) {
        return Observable.of(this.mapResponse(response.json()));
    } else if (response.status === 202) {
        return this.http.get(endPoint, {
            withCredentials: true,
            headers: this.headers
        });
    }
})
0

Source: https://habr.com/ru/post/1683158/


All Articles