What is routing? This article will give you an in-depth understanding of routing in Angular, I hope it will be helpful to you!
Routing introduction
Routing is a way to implement single-page applications, by listening to hash or Changes in history, rendering different components, play a role in local updates, avoiding requesting data from the server every time the URL changes. [Related tutorial recommendations: "angular tutorial"]
Routing configuration
Configure the routing module: approuter.module. Introduce the modified module into ts
const routes: Routes = [ { path: "first", component: FirstComponent }, { path: "parent", component: SecondComponent } ] @NgModule({ imports: [ CommonModule, // RouterModule.forRoot方法会返回一个模块,其中包含配置好的Router服务 // 提供者,以及路由库所需的其它提供者。 RouterModule.forRoot(routes, { // enableTracing: true, // <-- debugging purposes only // 配置所有的模块预加载,也就是懒加载的模块,在系统空闲时,把懒加载模块加载进来 // PreloadAllModules 策略不会加载被CanLoad守卫所保护的特性区。 preloadingStrategy: PreloadAllModules }) ], exports: [ FirstComponent, SecondComponent, RouterModule ], declarations: [ FirstComponent, SecondComponent ] }) export class ApprouterModule { }
app.module.ts:
imports: [ ApprouterModule ]
Redirect route:
const routes: Routes = [ { path: "", redirectTo: "first", pathMatch: "full" } ]
Wildcard routing:
const routes: Routes = [ // 路由器会使用先到先得的策略来选择路由。 由于通配符路由是最不具体的那个,因此务必确保它是路由配置中的最后一个路由。 { path: "**", component: NotFoundComponent } ]
Route lazy loading:
Configuring the lazy loading module can make the first screen The rendering speed is faster, and the corresponding module will only change when you click the lazy loading route.
const routes: Routes = [ { path: 'load', loadChildren: () => import('./load/load.module').then(m => m.ListModule), // CanLoadModule如果返回false,模块里面的子路由都没有办法访问 canLoad: [CanLoadModule] }, ]
Lazy loading module routing configuration:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoadComponent } from './Load.component'; import { RouterModule, Routes } from '@angular/router'; import { LoadTwoComponent } from '../../../app/components/LoadTwo/LoadTwo.component'; import { LoadOneComponent } from '../../../app/components/LoadOne/LoadOne.component'; const routes: Routes = [ { path: "", component: LoadComponent, children: [ { path: "LoadOne", component: LoadOneComponent }, { path: "LoadTwo", component: LoadTwoComponent } ] }, ] @NgModule({ imports: [ CommonModule, //子模块使用forChild配置 RouterModule.forChild(routes) ], declarations: [ LoadComponent, LoadOneComponent, LoadTwoComponent ] }) export class LoadModule { }
Lazy loading module routing navigation:
<a [routerLink]="[ 'LoadOne' ]">LoadOne</a> <a [routerLink]="[ 'LoadTwo' ]">LoadTwo</a> <router-outlet></router-outlet>
Route parameter passing:
const routes: Routes = [ { path: "second/:id", component: SecondComponent }, ]
//routerLinkActive配置路由激活时的类 <a [routerLink]="[ '/second', 12 ]" routerLinkActive="active">second</a>
Get route passing parameters:
import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-second', templateUrl: './second.component.html', styleUrls: ['./second.component.scss'] }) export class SecondComponent implements OnInit { constructor(private activatedRoute: ActivatedRoute, private router: Router) { } ngOnInit() { console.log(this.activatedRoute.snapshot.params); //{id: "12"} // console.log(this.activatedRoute); // 这种形式可以捕获到url输入 /second/18 然后点击<a [routerLink]="[ '/second', 12 ]">second</a> // 是可以捕获到的。上面那种是捕获不到的。因为不会触发ngOnInit,公用了一个组件实例。 this.activatedRoute.paramMap.pipe( switchMap((params: ParamMap) => { console.log(params.get('id')); return "param"; })).subscribe(() => { }) } gotoFirst() { this.router.navigate(["/first"]); } }
The queryParams parameter is passed by value, and the parameter acquisition is also through the dependency injection of the activated route
<!-- queryParams参数传值 --> <a [routerLink]="[ '/first' ]" [queryParams]="{name: 'first'}">first</a> <!-- ts中传值 --> <!-- this.router.navigate(['/first'],{ queryParams: { name: 'first' }); -->
Route guards: canActivate, canDeactivate, resolve, canLoad
The routing guard will return a value. If true is returned, execution continues, false prevents the behavior, and UrlTree navigates to the new route. The route guard may navigate to other routes, in which case it should return false. The route guard may depend on the server's value Decide whether to navigate, so you can also return Promise or Observable, and the route will wait The returned value is true or false. canActivate navigates to a route. canActivateChild navigates to a sub-route.
const routes: Routes = [ { path: "parent", component: ParentComponent, canActivate: [AuthGuard], children: [ // 无组件子路由 { path: "", canActivateChild: [AuthGuardChild], children: [ { path: "childOne", component: ChildOneComponent }, { path: "childTwo", component: ChildTwoComponent } ] } ], // 有组件子路由 // children: [ // { path: "childOne", component: ChildOneComponent }, // { path: "childTwo", component: ChildTwoComponent } // ] } ]
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate { canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any { // return true; // 返回Promise的情况 return new Promise((resolve,reject) => { setTimeout(() => { resolve(true); }, 3000); }) } }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class AuthGuardChild implements CanActivateChild { constructor() {} canActivateChild( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } }
parent.component.htmlRoute navigation:
<!-- 使用相对路径 --> <a [routerLink]="[ './childOne' ]">one</a> <!-- 使用绝对路径 --> <a [routerLink]="[ '/parent/childTwo' ]">two</a> <router-outlet></router-outlet>
canDeactivate route to leave, prompting the user that the information has not been saved.
const routes: Routes = [ { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] } ]
import { FirstComponent } from './components/first/first.component'; import { RouterStateSnapshot } from '@angular/router'; import { ActivatedRouteSnapshot } from '@angular/router'; import { Injectable } from '@angular/core'; import { CanDeactivate } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class CanDeactivateGuard implements CanDeactivate<any> { canDeactivate( component: any, route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): boolean { // component获取到组件实例 console.log(component.isLogin); return true; } }
Whether canLoad can enter the lazy loading module:
const routes: Routes = [ { path: 'load', loadChildren: () => import('./load/load.module').then(m => m.LoadModule), // CanLoadModule如果返回false,模块里面的子路由都没有办法访问 canLoad: [CanLoadModule] } ]
import { Route } from '@angular/compiler/src/core'; import { Injectable } from '@angular/core'; import { CanLoad } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class CanLoadModule implements CanLoad { canLoad(route: Route): boolean { return true; } }
resolve configures how long it takes to enter the routing, and you can obtain the data before entering the routing to avoid the white screen
const routes: Routes = [ { path: "resolve", component: ResolveDemoComponent, resolve: {detail: DetailResolver} ]
import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class DetailResolver implements Resolve<any> { constructor() { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any { return new Promise((resolve,reject) => { setTimeout(() => { resolve("resolve data"); }, 3000); }) } }
ResolveDemoComponent acquisition The value of resolve
constructor(private route: ActivatedRoute) { } ngOnInit() { const detail = this.route.snapshot.data.detail; console.log(detail); }
Listening to routing events:
constructor(private router: Router) { this.router.events.subscribe((event) => { // NavigationEnd,NavigationCancel,NavigationError,RoutesRecognized if (event instanceof NavigationStart) { console.log("NavigationStart"); } }) }
For more programming-related knowledge, please visit:Programming Video! !
The above is the detailed content of Deep dive into routing in Angular. For more information, please follow other related articles on the PHP Chinese website!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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 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.

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'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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
