Search code examples
angularrxjsangular6polling

No response while using takeWhile in angular 6 for polling api using http


I have a client API which i want to poll till it returns success result, this API returns a response with following JSON.

{
"count": 0,
"meta": {
    "status": "PENDING",
    "total": 3185,
    "completion_percentage": 0,
    "total_available": 0,
    "hotels_filtered": 0,
    "offers": 0
},
data:[]
}

and a positive result should contain the status ='COMPLETED' and data filed will include the result in data, I tried using takeWhile from 'rxjs'

component.ts

var headers = { headers: new HttpHeaders({ 'x-user-agent':'M;B2B' }) };

var url='https://api.xyz.com/hotels/v1/search/entity/27548283?apikey=1234567'

this.http.get(url,headers)
.pipe(
  takeWhile((data)=>JSON.parse(JSON.stringify(data)).meta.status==='COMPLETED') 
)
.subscribe((result)=>{
  console.log(result);

},(err)=>{
  console.log(err);

})

But unfortunately I am not getting anything in to subscribe log method, is this a right method?

My angular version is 6.


Solution

  • I think you are looking for retryWhen operator:

    let httpGet$ = this.http.get(url, headers);
    let retryFilter = data => JSON.parse(JSON.stringify(data)).meta.status !== 'COMPLETED';
    
    httpGet$.pipe(
      map(data => {
        if(retryFilter(data)) {
          throw 'retry';
        }
        return val;
      }),
      retryWhen(_ =>
        // retry after 3 sek when retryFilter (above) failed
        _.pipe(delayWhen(_ => timer(3000))),
      )
    ).subscribe(result => console.log(result));