Loading data before components using Router resolver in Angular

As the name suggests, we can add a resolve function to the route which loads the component that has an API call to do. This will cause the component to be only loaded and displayed by Angular once the API call (or whatever else we define) is loaded.

Create a separate class which we’ll have the resolver functionality

// resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';

@Injectable()
export class Resolver implements Resolve<Observable<string>> {
  constructor(private api: ApiService) { }

  resolve() {
    return this.api.getProducts();
  }
}

Add this class as a provider

// app.module.ts
import { Resolver } from './resolver';
// ...
providers: [Resolver],

app-routing.module.ts

// app-routing.module.ts
import { Resolver } from './resolver';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'products', component: ProductsComponent, resolve: { products: Resolver } }
];
// products.component.ts
import { ActivatedRoute } from '@angular/router';
// ...
constructor(private route: ActivatedRoute) { }
products;
ngOnInit() {
  this.products = this.route.snapshot.data.products;
}

Access to Route Params

import { Injectable } from '@angular/core';
import { HnService } from './hn.service';

import { Resolve } from '@angular/router';

import { ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class HnResolver implements Resolve<any> {
  constructor(private hnService: HnService) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.hnService.getPost(route.paramMap.get('id'));
  }
}

References
https://blog.fullstacktraining.com/loading-data-before-components-in-angular/
https://alligator.io/angular/route-resolvers/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.