0

Setup

  • Angular 13.2.0
  • Ngrx 13.0.2
  • Backend: Spring Boot

Goal

When the backend is not running i want to retry the url x-times.

What works so far

fetchEntities$ = createEffect(() =>
    this.actions$.pipe(
      ofType(DoctransActions.fetchEntities),
      exhaustMap(action =>
        this.http.get<DoctransResponse>(`${this.apiUrl}/some url`).pipe(
          map(response => {
            return action to set entities
          }),
          catchError((err) => {
            return action for error
        )
      )
    )
  );

Interceptor

@Injectable()
export class RetryInterceptor implements HttpInterceptor {

  constructor(private store: Store<AppState>) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      retryWhen(error =>
        error.pipe(
          concatMap((error, count) => {
            if (count < environment.http.retry && environment.http.retryAtCodes.includes(error.status)) {
              this.store.dispatch(retryFetch({errorRespone: error, retryCount: (count+1)}));
              return of(error);
            }
            return throwError(error);
          }),
          delay(environment.http.delay)
        )
      )
    )
  }
}

The retryFetch Action sets an error for the user that the system is trying to connect.

Question

Is there a better way of doing this?

Solution

See: Angular - ngrx - Effect for continually getting data from server

EvenSource does automatic reconnecting

Hesk
  • 307
  • 4
  • 16
  • Why don't you use ngrx with a socket connection so you can get data seamlessly? – Shafkhan Mar 14 '22 at 08:37
  • Same answer from this https://stackoverflow.com/questions/71464756/angular-ngrx-effect-for-continually-getting-data-from-server . Websocket is the best way for this, as well. – Pterrat Mar 14 '22 at 08:44

1 Answers1

0

This is also fine. See the following for more inspiration:

timdeschryver
  • 14,415
  • 1
  • 19
  • 32