A common way to get and display the data from some API is routing a specific user to an angular component, and therafter calling a method present in service from the component’s 'ngOnInit' hook to fetch the necessary information. In this approach we often display some loading indicator till the response is arrived from the server.
However, there is another way called 'route resolver' which allows us to get the necessary data prior to navigation to a particular route.
Tip- Resolvers should not be overused
We should load only the relevant data through resolvers to display the important sections of the page and rest of the data should be fetched asynchronously.
// main.ts import { TransactionResolver } from './resolvers/transaction.resolver.ts'; export const routes: RouterConfig = [ { path: 'transactions/:id', component: TransactionComponent, resolve: { transaction: TransactionResolver } } ]; bootstrap(AppComponent, [ provideRouter(routes) ])
// transaction.resolver.ts import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { TransactionService } from '../services/transaction.service'; @Injectable() export class TransactionResolver implements Resolve{ constructor( private transactionService: TransactionService ) {} resolve(route: ActivatedRouteSnapshot): Observable { return this.transactionService.getById(route.params.id); } }