CodeMan03
CodeMan03

Reputation: 226

Rxjs repeat call until a value is found

In angular 8 I have a method that needs to keep repeating until i get a particular success message from the server.

In my webapi method it has a call that pings another server and the other server sends back an api key. I need to keep calling this method until an api key is generated and finally sent back. This is the need for the retry interval.

My issue is the response == success call is never hit.

     return new Promise((resolve, reject) => {
        this.http.get<any>(url)
        pipe(
        map(response => {
          if(response == 'Success'){   <--- Not getting hit.
              resolve(true);
          }
        }),
        timeout(500),           
        retry(),
        delay(1500),
        repeat());
    })

Upvotes: 0

Views: 3806

Answers (2)

julianobrasil
julianobrasil

Reputation: 9357

If you checkout here, I think you'll find an answer. I think this fits your question.

return new Promise((resolve, reject) => {
  this.http.get<any>(url).pipe(
    tap(response => {
      if(response == 'Success'){   <--- Not getting hit.
        resolve(true);
      } else {
        // will be catch on retryWhen
        throw 'ERROR';
      }
    }),
    // if any errors, wait 1.5s and try again
    retryWhen(errors => errors.pipe(delayWhen(_ => timer(1500)))
  ).subscribe();
});

Upvotes: 0

Jasdeep Singh
Jasdeep Singh

Reputation: 8301

Not sure about your primary task but can definitely help you with the issues in code.

  1. I don't think you need promises here. You can develop your code without them.
  2. You need to subscribe to your observable in order to emit values from observable.
  3. You need to use tap operator instead of map operator, as you need to check existence of value

    this.http.get<any>(url)
    pipe(
    tap(response => {
      if(response == 'Success'){   <--- Not getting hit.
        alert('successful data')
      }
    }),
    timeout(500),           
    retry(),
    delay(1500),
    repeat()).subscribe(x => console.log(x));
    })  
    

Upvotes: 2

Related Questions