I have successfully implemented an NGRX Data entity service and now I'm looking to preload data before accessing a route by using a resolver.
import { Injectable } from "@angular/core";
import {
ActivatedRouteSnapshot,
Resolve,
RouterStateSnapshot,
} from "@angular/router";
import { Observable, race } from "rxjs";
import { filter, first, tap, mapTo } from "rxjs/operators";
import { ExerciseEntityService } from "./exercise-entity.service";
@Injectable()
export class ExercisesResolver implements Resolve<boolean> {
constructor(private exercisesService: ExerciseEntityService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.exercisesService.loaded$.pipe(
tap((loaded) => {
if (!loaded) {
this.exercisesService.getAll();
}
}),
filter((loaded) => !!loaded),
first()
);
}
}
The challenge arises when the service responds with an error. How can we manage errors while still resolving the route? One approach I tried is using the following code:
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
Resolve,
RouterStateSnapshot
} from '@angular/router';
import { Observable, race } from 'rxjs';
import { filter, first, tap, mapTo } from 'rxjs/operators';
import { ExerciseEntityService } from './exercise-entity.service';
@Injectable()
export class ExercisesResolver implements Resolve<boolean> {
constructor(private exercisesService: ExerciseEntityService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return race(
this.exercisesService.loaded$.pipe(
tap((loaded) => {
if (!loaded) {
this.exercisesService.getAll();
}
}),
filter((loaded) => !!loaded),
first()
),
this.exercisesService.errors$.pipe(mapTo(true))
);
}
}