search
HomeWeb Front-endJS TutorialLet's talk about how to obtain data in advance in Angular Route

How to get data in advance in Angular Route? The following article will introduce to you how to obtain data in advance from Angular Route. I hope it will be helpful to you!

Let's talk about how to obtain data in advance in Angular Route

Getting ahead of time means getting the data before it is presented 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 it to a public preloaded navigation. [Related tutorial recommendations: "angular tutorial"]

Why should you use Resolver

Resolver Plays the role of 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 when the user data is loaded, and then when the data is returned, fill the form and hide the loader.

Usually, we will get the data in the ngOnInit() hook function of the component. In other words, after the component is loaded, we initiate a data request.

Operation in ngOnInit(), we need to add loader display in 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 that applies to 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.

Using Resolver in an application

In order to use resolver in an application, 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 application of resolver. A resolver is a middleware service, so we will create a service.

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

--skipTests=true Skip generating test files A service is created in the

src/app/resolvers folder. resolver There is a resolve() method in the interface, which has two parameters: route (an instance of ActivatedRouteSnapshot) and state (an instance of RouterStateSnapshot).

loader Normally all AJAX requests are written in ngOnInit(), but the logic will be in resolver Implemented in, replacing 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 data through routing and display it in the component.

Create the service and write the logic to get the list data

$ ng g s 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 Ready, it’s time to get the data for post 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 g c 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 routing 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 a HTTP request, then allow the component to initialize when the HTTP request returns successfully. The route will assemble the data returned by the HTTP request.

How to apply a preloaded navigation

To show the user that a request is in progress, we write a common and simple ## in AppComponent #loader. You can customize it as needed.

app.component.html

Loading...
<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;
        }
      }
    });
  }
}

当导航开始,isLoader 值被赋予 true,页面中,你将看到下面的效果。

Lets talk about how to obtain data in advance in Angular Route

resolver 处理完之后,它将会被隐藏。

现在,是时候从路由中获取值并将其展示出来。

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"];
  }
}

如上所示,post 的值来自 ActivatedRoute 的快照信息 data。这值都可以获取,只要你在路由中配置了相同的信息。

我们在 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 片段样式让其看起来更美观。

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;
}

推荐使用 scss 预处理器编写样式

从路由中获取数据之后,它会被展示在 HTML 中。效果如下快照。

Lets talk about how to obtain data in advance in Angular Route

至此,你已经了解完怎么应用 resolver 在你的项目中了。

总结

结合用户体验设计,在 resolver 的加持下,你可以提升你应用的表现。了解更多,你可以戳官网

本文是译文,采用的是意译的方式,其中加上个人的理解和注释,原文地址是:

https://www.pluralsight.com/guides/prefetching-data-for-an-angular-route

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Let's talk about how to obtain data in advance in Angular Route. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools