I am developing an angular project, I need to call a backend api, if it's not return 200, then i need to call this api every 30 seconds, until I get 200 OK.
I am using angular, the format I usually call an backend api is this:
this.productServices.onProductBuy(product_id).subscribe(response => {
console.log(response)
});
onProductBuy()
contains some calling api code, it's just simply a get request
If a HTTP 200 is not received for this onProdcutBuy api, I need to call this api one more time until I get the 200.
CodePudding user response:
This should do the trick:
this.productServices.onProductBuy(product_id).pipe(
retry({
delay: 30 * 1000
} as any)
).subscribe(response => {
console.log(response)
});
This retry an infinite amount of times and also add a delay of 30 second. The type definition of retry
seems to be broken with the version I am using. That's why I had to use as any
.
But the source code shows, that retry
accepts an object with a delay property:
export interface RetryConfig {
/**
* The maximum number of times to retry. If `count` is omitted, `retry` will try to
* resubscribe on errors infinite number of times.
*/
count?: number;
/**
* The number of milliseconds to delay before retrying, OR a function to
* return a notifier for delaying. If a function is given, that function should
* return a notifier that, when it emits will retry the source. If the notifier
* completes _without_ emitting, the resulting observable will complete without error,
* if the notifier errors, the error will be pushed to the result.
*/
delay?: number | ((error: any, retryCount: number) => ObservableInput<any>);
/**
* Whether or not to reset the retry counter when the retried subscription
* emits its first value.
*/
resetOnSuccess?: boolean;
}
export function retry<T>(count?: number): MonoTypeOperatorFunction<T>;
export function retry<T>(config: RetryConfig): MonoTypeOperatorFunction<T>;
CodePudding user response:
You could use rxjs retry:
this.productServices.onProductBuy(product_id)
.pipe(retry(2)) // <-- Here
.subscribe(response => {
console.log(response)
});
With the above it will retry twice. If you'd like to retry forever, just don't add a number to it, it will keep retrying until a success is received:
this.productServices.onProductBuy(product_id)
.pipe(retry()) // <-- Here
.subscribe(response => {
console.log(response)
});
Don't forget to avoid the memory leak trap with subscriptions.