Rich
Rich

Reputation: 561

Retry all HTTP calls if one fails in Angular 2 when one is dependant on another

Taking this Angular 2 code which makes a http call to './customer.json' and then uses a url returned in that to make a further call. How do I make it retry both calls if the second one fails using the rxjs retry method? Currently it just seems to retry the second one.

this.http.get('./customer.json')
.map((res: Response) => {
    this.customer = res.json();
    return this.customer;
})
.flatMap((customer) => {
    return this.http.get(customer.contractUrl)).map((res: Response) => res.json()
})
.retry(1);

So if this.http.get(customer.contractUrl)) fails how do I make it retry both http.get('./customer.json') and this.http.get(customer.contractUrl)) again.

Upvotes: 1

Views: 1594

Answers (1)

Rich
Rich

Reputation: 561

I'm not sure why my original code doesn't seem to work but I tried using the catch method instead and it seems to work.

makeCall(isRetry = false){
    return this.http.get('./customer.json')
        .map((res: Response) => {
            this.customer = res.json();
            return this.customer;
        })
        .flatMap((customer) => {
            return this.http.get(customer.contractUrl)).map((res: Response) => res.json()
        })
        .catch((err) => {
            if (isRetry === false){
                return this.makeCall(true);
            }

            return Observable.throw(err);
        });
}

I'll make some jsbins and see if I can figure it out

Upvotes: 1

Related Questions