Search code examples
angularangular-routingresolver

Do I need to write a Route Resolver for every service call that implements a new interface?


I have a question about routing in Angular 4, especially dealing with resolving the data.

My app will benefit greatly by implementing a route resolver; however, I am working on a complex web app and In one of my routes (a contact page) there are several components being rendered, each with a different service call to the back end. Each call is implementing a different interface. This is due to database restrictions.

Is their a way I can write 1 resolver for each of my services, or do I need to write a resolver for each service call that implements a new interface?


Solution

  • You can do everything in a single resolver, like so:

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    
         return Observable.forkJoin(
             this.someService.apiCallA(),
             this.someService.apiCallB(),
             this.someService.apiCallC(),
          )
          .map(([resA, resB, resC]: [ResponseAType, ResponseBType, ResponseCType]) => {
                return {
                   aData: resA,
                   bData: resB,
                   cData: resC
                };
    
          });
    
    }
    

    Then in your main page component:

    constructor(private aRoute: ActivatedRoute) {
    
          aRoute.data.subscribe((data: any) => {
             // You can find aData, bData, and cData here inside of data
             // Pass them down into the components that need them
          });
    
       }