godhar
godhar

Reputation: 1392

Rxjs interval is not polling observable server API call

I am trying to poll an API call to my backend. The idea is that the server will send a 202 error until it has finished processing a job and after so many requests will return a 200 with some results. I don't want the error to kill the stream. The API call is only made once.

"rxjs": "~6.4.0", "@angular/core": "~8.2.14"

Kick-off code:

     onSubmit() {
    return this.scraperService.postUrl(this.form.value.url)
      .pipe(
        switchMap( val => {
          return this.scraperService.pollUntilTaskFinished(val);
        })
      ).subscribe( val => console.log(val))
  }

Service code:

     postUrl(url: string): Observable<any> {
    return this.http.post('/api/start', {url})
      .pipe(
        map((res: { jobId: string }) => {
          if (res.jobId) {
            return res.jobId;
          }
        }));
  }
  pollUntilTaskFinished(jobId): Observable<any> {
        return interval(2000)
          .pipe(
            switchMap(() => this.http.get(`/api/results/${jobId}`)))
          .pipe(
            catchError(err => this.handleError(err)),
            map(res => console.log(res)));
      }
   handleError(data: HttpErrorResponse) {
    if (data.status === 202) {
      return of('continue');
    }
  }

How can I ensure that the interval repeats until I get a 200 with the JSON I need?

Upvotes: 1

Views: 160

Answers (1)

martin
martin

Reputation: 96891

If you don't want to dispose the chain you'll have to catch the error before it's propagated to the main chain. This means catching it inside switchMap():

this.http.get(`/api/results/${jobId}`))
  .pipe(
    catchError(err => this.handleError(err)),
  )

Upvotes: 1

Related Questions