Home > Article > Web Front-end > Deep dive into routing in Angular
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!