Retain a request after 5 seconds in case of error

Asked

Viewed 90 times

0

I need to retain my http request after 5 seconds in case of error.

I tried to implement with retryWhen but I get:

Property 'retryWhen' does not exist on type 'Observable'. [2339]

I tried so:

  listaDepartamentos(){
    this.myservice.consultaDepartamentos()
    .pipe(
      take(1)
    )
    .retryWhen(error => {
      return error
         .flatMap((error: any) => {
            if(error.status  === 503) {
              return Observable.of(error.status).delay(5000)
            }
            return Observable.throw({error: 'No retry'});
         })
         .take(5)
         .concat(Observable.throw({error: 'Sorry, there was an error (after 5 retries)'}));
      });
    .subscribe((res) => {
     console.log(res)
    },
    (err) => {
      console.log(err)

    })
  }

At my service:

consultaDepartamentos():Observable<any>{
    return this._http.get<any>(AppSettings.API_ENDPOINT + 'global/departamento/listar',
    {observe: 'response'})
}
  • You are importing the operator?

  • yes, he finds the operator

  • 1

    take a look at this example, maybe you can help https://stackblitz.com/edit/angular-cwnknr?file=app%2Fapp.component.ts

  • I’ll try. you could add an answer explaining the code?

1 answer

1


From rxjs 5.5, the recommended way to chain operators is by using the pipe. To documentation explains the why.

Instead of doing:

$observable.map(...)
    .filter(...)
    .mergeMap(...)
    .subscribe(...)

You must do so:

import { map, filter, mergeMap } from 'rxjs/operators';

$observable.pipe(
    map(...),
    filter(...),
    mergeMap(...),
)
.subscribe(...)

Your code would look like this:

this.myservice.consultaDepartamentos()
  .pipe(
    take(1),
    retryWhen(error => error.pipe(
        flatMap((error: any) => {
            if(error.status === 503) {
              return of(error.status).pipe(delay(5000))
            }
            return throwError({error: 'No retry'});
        }),
        take(5),
        concat(throwError({error: 'Sorry, there was an error (after 5 retries)'})),
    ))
  )
  .subscribe((res) => {
      console.log(res)
    },
    (err) => {
      console.log(err)
    }
  )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.