Fetching ahead of time means getting the data before it is displayed on the screen. In this article, you will learn how to obtain data before routing changes. Through this article, you will learn to use resolver
, apply resolver
in Angular App
, and apply them to a common preloaded navigation. [Related tutorial recommendation: "angular tutorial"]
Resolver
Resolver
plays the role of a middleware service between routing and components. Suppose you have a form with no data, and you want to present an empty form to the user, display a loader
while the user data is loaded, and then when the data is returned, populate the form and hide loader
.
Usually, we get data in the component's ngOnInit()
hook function. In other words, after the component is loaded, we initiate a data request.
Operating in ngOnInit()
, we need to add loader
display to its routing page after each required component is loaded. Resolver
can simplify the addition and use of loader
. Instead of adding loader
to every route, you can just add one loader
for each route.
This article will use examples to analyze the knowledge points of resolver
. So that you can remember it and use it in your projects.
Resolver
in ApplicationsIn order to use resolver
in applications, you need to prepare some interfaces. You can simulate it through JSONPlaceholder without developing it yourself.
JSONPlaceholder
is a great interface resource. You can use it to better learn related concepts of the front end without being constrained by the interface.
Now that the interface problem is solved, we can start the resolver
application. A resolver
is a middleware service, so we will create a service.
$ ng gs resolvers/demo-resolver --skipTests=true
--skipTests=true skips generating test files
. A service is created in src/app/resolvers
folder. There is a resolve()
method in the resolver
interface, which has two parameters: route
(an instance of ActivatedRouteSnapshot
) and state
(an instance of RouterStateSnapshot
).
loader
usually writes all AJAX
requests in ngOnInit()
, but the logic will be implemented in resolver
instead of ngOnInit()
.
Next, create a service to obtain the list data in JSONPlaceholder
. Then call it in resolver
, and then configure resolve
information in the route (the page will wait) until resolver
is processed. After resolver
is processed, we can obtain the data through routing and display it in the component.
$ ng gs services/posts --skipTests=true
Now that we have successfully created the service, it is time to write the logic for an AJAX
request.
The use of model
can help us reduce errors.
$ ng g class models/post --skipTests=true
post.ts
export class Post { id: number; title: string; body: string; userId: string; }
model
is ready, it’s time to get the data of post
.
post.service.ts
import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Post } from "../models/post"; @Injectable({ providedIn: "root" }) export class PostsService { constructor(private _http: HttpClient) {} getPostList() { let URL = "https://jsonplaceholder.typicode.com/posts"; return this._http.get<Post[]>(URL); } }
Now, this service can be called at any time.
demo-resolver.service.ts
import { Injectable } from "@angular/core"; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; import { PostsService } from "../services/posts.service"; @Injectable({ providedIn: "root" }) export class DemoResolverService implements Resolve<any> { constructor(private _postsService: PostsService) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this._postsService.getPostList(); } }
Post list data returned from resolver
. Now, you need a route to configure resolver
, get the data from the route, and then display the data in the component. In order to perform routing jumps, we need to create a component.
$ ng gc components/post-list --skipTests=true
To make the route visible, add router-outlet
in app.component.ts
.
<router-outlet></router-outlet>
Now, you can configure the app-routing.module.ts
file. The following code snippet will help you understand the route configuration resolver
.
app-routing-module.ts
import { NgModule } from "@angular/core"; import { Routes, RouterModule } from "@angular/router"; import { PostListComponent } from "./components/post-list/post-list.component"; import { DemoResolverService } from "./resolvers/demo-resolver.service"; const routes: Routes = [ { path: "posts", component: PostListComponent, resolve: { posts: DemoResolverService } }, { path: "", redirectTo: "posts", pathMatch: "full" } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
A resolve
has been added to the routing configuration, which will initiate an HTTP
request and then allow the component to initialize when HTTP
request returns successfully. The route will assemble the data returned by HTTP
request.
to show the user that a request is in progress, we write a public and simple loader
in AppComponent
. You can customize it as needed.
app.component.html
<div class="loader" *ngIf="isLoader"> <div>Loading...</div> </div> <router-outlet></router-outlet>
app.component.ts
import { Component } from "@angular/core"; import { Router, RouterEvent, NavigationStart, NavigationEnd } from "@angular/router"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComponent { isLoader: boolean; constructor(private _router: Router) {} ngOnInit() { this.routerEvents(); } routerEvents() { this._router.events.subscribe((event: RouterEvent) => { switch (true) { case event instanceof NavigationStart: { this.isLoader = true; break; } case event instanceof NavigationEnd: { this.isLoader = false; break; } } }); } }
When the navigation starts, isLoader
value is assigned true
, and you will see the following effect on the page.
When resolver
is finished processing, it will be hidden.
Now, it's time to get the value from the route and display it.
port-list.component.ts
import { Component, OnInit } from "@angular/core"; import { Router, ActivatedRoute } from "@angular/router"; import { Post } from "src/app/models/post"; @Component({ selector: "app-post-list", templateUrl: "./post-list.component.html", styleUrls: ["./post-list.component.scss"] }) export class PostListComponent implements OnInit { posts: Post[]; constructor(private _route: ActivatedRoute) { this.posts = []; } ngOnInit() { this.posts = this._route.snapshot.data["posts"]; } }
As shown above, the value of post
comes from the snapshot information data
of ActivatedRoute
. Both of these values can be obtained as long as you configure the same information in the route.
We render as follows in HTML
.
<div class="post-list grid-container"> <div class="card" *ngFor="let post of posts"> <div class="title"><b>{{post?.title}}</b></div> <div class="body">{{post.body}}</div> </div> </div>
CSS
fragment styles make it look more beautiful.
port-list.component.css
.grid-container { display: grid; grid-template-columns: calc(100% / 3) calc(100% / 3) calc(100% / 3); } .card { margin: 10px; box-shadow: black 0 0 2px 0px; padding: 10px; }
It is recommended to use scss preprocessor to write styles.
After getting the data from the route, it will be displayed in HTML
. The effect is as follows: snapshot.
At this point, you have learned how to use resolver
in your project.
Combined with user experience design, and with the help of resolver
, you can improve the performance of your application. To learn more, you can visit the official website.
This article is a translation, using free translation, with personal understanding and comments added. The original address is:
https://www.pluralsight.com/guides/prefetching-data-for-an-angular-route