moris62
moris62

Reputation: 1045

how to keep calling the api until the result is retrieved in Angular

I have a api which i need to keep calling it until the result is ready to fetch

SendToBank(){

 this.http.get(`http://localhost:44301/consentinitiation/${this.qid}`).subscribe(s=>{

 this.qrcodelink=s["qrCodeLink"];

 });

qrCodeLink is the property inside my result which i need it,it has other properties as well ,sometimes after 5 seconds result is there sometimes 10 seconds but i need to put a loader in my front end and keep calling it until i get the result ,any help?

Upvotes: 1

Views: 823

Answers (2)

vsnikhilvs
vsnikhilvs

Reputation: 576

You can use interval with a time period of your choice and call the api inside its subscription along with checking if the api response is what you need. If the response is what you need, you can unsubscribe from the interval.

Upvotes: 0

H3AR7B3A7
H3AR7B3A7

Reputation: 5251

You can pipe the observable to retry the request. You can use an interval or a maximum number of retries:

this.http.get("`http://localhost:44301/consentinitiation/${this.qid}`")
  .pipe(retryWhen(_ => {
    return interval(5000)
  }))
  .subscribe(result => ...)
}

Or better practice:

this.http.get("`http://localhost:44301/consentinitiation/${this.qid}`")
  .pipe(
    retry(3),
    catchError(() => { // Handle error
      ...
    }),
    ... // Some more pipes
  )
  .subscribe(result => ...)
}

Anything other than the retry is optional of course, you can pipe through anything you want...

Upvotes: 1

Related Questions