Search code examples
angularrxjsangular5angular4-router

Angular4 Fetch data before navigating Route Resolve


I am trying to use the Angular Route Resolve to fetch component data before the route is activated.

All the examples I have seen call one method in the service and return, I have 5 different methods in the service which need to be called b4 the component is activated.

Below is example of what I am trying to achieve, the ContactService has 3 methods that all need to be called - how can I return all 3 methods in one call?

Any pointers appreciated.

Contact-Resolver.ts - below

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ContactsService } from './contacts.service';

@Injectable()
export class ContactResolve implements Resolve<Contact>
{

  constructor(private contactsService: ContactsService) {}

  resolve(route: ActivatedRouteSnapshot)
  {
    return this.contactsService.getContact(route.paramMap.get('id')); //method in Service
  }

//  return this.contactsService.getCities(); //Another method in Service that also needs to be called

 // return this.contactsService.getAllParts(); //Another method in Service that also needs to be called


}

Solution

  • You can use just forkJoin that will wait until all source Observable complete:

    resolve(route: ActivatedRouteSnapshot) {
      return Observable.forkJoin(
        this.contactsService.getContact(route.paramMap.get('id')),
        this.contactsService.getCities(),
        this.contactsService.getAllParts()
      );
    }
    

    All results will be available in a single array with 3 items.