Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

Prefetching Data for an Angular Route

Gaurav Singhal

  • Mar 17, 2020
  • 9 Min read
  • 29,028 Views
  • Mar 17, 2020
  • 9 Min read
  • 29,028 Views
Languages Frameworks and Tools
Angular

Introduction

Prefetching means getting data before it needs to be rendered on a screen. In this Guide you will learn how to fetch data even before a routing change. By the end of this Guide, you will be able to use a resolver, implement a resolver in an Angular app, and apply a common preloader navigation.

Why You Should Use a Resolver

A resolver is a middleware service that plays a role in between a route and a component. Suppose you have a form and want it to first show an empty form to the user with no data, then display a loader while it fetches the user's data, and then hide the loader and fill the form once the data has arrived.

Usually, we get the data using ngOnInit(), which is one of the lifecycle hooks of the Angular component. It means that after the component is loaded, we hit the request for the data and toggle the loader.

We attach a loader in every route that requires data to show just after the component is loaded. A resolver is used to minimize the use of the loader. Instead of attaching the loader in every route, you can add only one loader that works for every route.

This Guide will explain each point of the resolver with an example, so you can use it as it is in your project with the complete picture in mind.

Implementing a Resolver in an App

To implement the resolver, you'll need a couple of APIs for the app. Instead of creating an API here, you can use fake APIs from JSONPlaceholder. JSONPlaceholder is one of the best API sources for learning frontend concepts without bothering about APIs.

Now that the API issues have been solved, you can start on the resolver. A resolver is nothing but a middleware service, so you'll create a service.

1$ ng g s resolvers/demo-resolver --skipTests=true
shell

The src/app/resolvers folder has been created in the service. The resolver interface has a resolve() method with two parameters: route, the instance of ActivatedRouteSnapshot, and state, the instance of RouterStateSnapshot.

The loader used to write all AJAX requests in ngOnInit(), but that logic will be replaced with ngOnInit() in the resolver.

Next, create a service with logic to get the list of posts from JSONPlaceholder. Then call the function in the resolver and configure the route for a resolve that will wait until the resolver gets resolved. After resolving the resolver, we will get the data from the route and display it in the component.

Create a Service and Write Logic to Get the Post List

1$ ng g s services/posts --skipTests=true
shell

Now that the service has been successfully created, it's time to write logic to make an AJAX request.

This model uses best practices to help minimize errors.

1$ ng g class models/post --skipTests=true
shell

post.ts

1export class Post {
2  id: number;
3  title: string;
4  body: string;
5  userId: string;
6}
ts

Now the model is ready to get the list of posts.

post.service.ts

1import { Injectable } from "@angular/core";
2import { HttpClient } from "@angular/common/http";
3import { Post } from "../models/post";
4
5@Injectable({
6  providedIn: "root"
7})
8export class PostsService {
9  constructor(private _http: HttpClient) {}
10
11  getPostList() {
12    let URL = "https://jsonplaceholder.typicode.com/posts";
13    return this._http.get<Post[]>(URL);
14  }
15}
ts

Now the service is ready to be called.

demo-resolver.service.ts

1import { Injectable } from "@angular/core";
2import {
3  Resolve,
4  ActivatedRouteSnapshot,
5  RouterStateSnapshot
6} from "@angular/router";
7import { PostsService } from "../services/posts.service";
8
9@Injectable({
10  providedIn: "root"
11})
12export class DemoResolverService implements Resolve<any> {
13  constructor(private _postsService: PostsService) {}
14
15  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
16    return this._postsService.getPostList();
17  }
18}
ts

The post list is returned from the resolver. Now you need a routing to configure the resolver, get the data from the route, and display it in the component. To make a routing, you'll need to make a component.

1$ ng g c components/post-list --skipTests=true
shell

To make the route visible, add router-outlet in the app.component.ts.

1<router-outlet></router-outlet>
html

Now you can configure the app-routing.module.ts. The following snippet helps you to understand the routing configuration in the resolver.

app-routing.module.ts

1import { NgModule } from "@angular/core";
2import { Routes, RouterModule } from "@angular/router";
3import { PostListComponent } from "./components/post-list/post-list.component";
4import { DemoResolverService } from "./resolvers/demo-resolver.service";
5
6const routes: Routes = [
7  {
8    path: "posts",
9    component: PostListComponent,
10    resolve: {
11      posts: DemoResolverService
12    }
13  },
14  {
15    path: "",
16    redirectTo: "posts",
17    pathMatch: "full"
18  }
19];
20
21@NgModule({
22  imports: [RouterModule.forRoot(routes)],
23  exports: [RouterModule]
24})
25export class AppRoutingModule {}
ts

A resolve has been added to the route configuration that will make an HTTP request and allow the component to initialize after the HTTP request is successful. The route will collect data fetched by the HTTP request.

How to Apply a Common Preloader Navigation

To show the user that a request is in progress, write a common simple loader in AppComponent. You can customize it per your requirements.

app.component.html

1<div class="loader" *ngIf="isLoader">
2  <div>Loading...</div>
3</div>
4<router-outlet></router-outlet>
html

app.component.ts

1import { Component } from "@angular/core";
2import {
3  Router,
4  RouterEvent,
5  NavigationStart,
6  NavigationEnd
7} from "@angular/router";
8
9@Component({
10  selector: "app-root",
11  templateUrl: "./app.component.html",
12  styleUrls: ["./app.component.scss"]
13})
14export class AppComponent {
15  isLoader: boolean;
16
17  constructor(private _router: Router) {}
18
19  ngOnInit() {
20    this.routerEvents();
21  }
22
23  routerEvents() {
24    this._router.events.subscribe((event: RouterEvent) => {
25      switch (true) {
26        case event instanceof NavigationStart: {
27          this.isLoader = true;
28          break;
29        }
30        case event instanceof NavigationEnd: {
31          this.isLoader = false;
32          break;
33        }
34      }
35    });
36  }
37}
ts

When navigation starts, the isLoader value will be true, and you'll see the following output.

imgur

After the resolver resolves, it will be hidden.

Now it's time to fetch the value from the route and display it on the list.

port-list.component.ts

1import { Component, OnInit } from "@angular/core";
2import { Router, ActivatedRoute } from "@angular/router";
3import { Post } from "src/app/models/post";
4
5@Component({
6  selector: "app-post-list",
7  templateUrl: "./post-list.component.html",
8  styleUrls: ["./post-list.component.scss"]
9})
10export class PostListComponent implements OnInit {
11  posts: Post[];
12
13  constructor(private _route: ActivatedRoute) {
14    this.posts = [];
15  }
16
17  ngOnInit() {
18    this.posts = this._route.snapshot.data["posts"];
19  }
20}
ts

Here, the value comes from the data in the snapshot of ActivatedRoute. The value is available through the same route that you've configured in routing.

This is what the value looks like in HTML.

1<div class="post-list grid-container">
2  <div class="card" *ngFor="let post of posts">
3    <div class="title"><b>{{post?.title}}</b></div>
4    <div class="body">{{post.body}}</div>
5  </div>
6</div>
html

This CSS snippet will make it prettier.

port-list.component.css

1.grid-container {
2  display: grid;
3  grid-template-columns: calc(100% / 3) calc(100% / 3) calc(100% / 3);
4}
5.card {
6  margin: 10px;
7  box-shadow: black 0 0 2px 0px;
8  padding: 10px;
9}
css

After the data is fetched from the route, it will be displayed in HTML. The list will look like the below snippet.

imgur

At this point you've done everything you have to do to implement the resolver in your project.

Conclusion

You can improve your app's performance as well as UX with the help of a resolver. It's not possible to cover all the conditions in one article, but you can explore it more here.