Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand routing in Angular

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to understand routing in Angular. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

! In Angular, routing is based on modules, and each module can have its own route.

Get started quickly

Create page components, Layout components, and Navigation components for routing

Create the home page component ng g c pages/home

Create ng g c pages/about about our page component

Create a layout component ng g c pages/layout

Create navigation component ng g c pages/navigation

Create routing rules

/ / app.module.tsimport {Routes} from "@ angular/router" const routes: Routes = [{path: "home", component: HomeComponent}, {path: "about", component: AboutComponent}]

Introduce the routing module and start it

/ / app.module.tsimport {RouterModule, Routes} from "@ angular/router" @ NgModule ({imports: [RouterModule.forRoot (routes, {useHash: true})],}) export class AppModule {}

Add routing socket

Define links in the navigation component

Home page about our matching rules

1. Redirect

Const routes: Routes = [{path: "home", component: HomeComponent}, {path: "about", component: AboutComponent}, {path: "", / / redirect redirectTo: "home", / / exactly match pathMatch: "full"}]

2. 404 pages

Const routes: Routes = [{path: "home", component: HomeComponent}, {path: "* *", component: NotFoundComponent}] routing parameters 1. Query parameters about our import {ActivatedRoute} from "@ angular/router" export class AboutComponent implements OnInit {constructor (private route: ActivatedRoute) {} ngOnInit (): void {this.route.queryParamMap.subscribe (query = > {query.get ("name")})}}

2. Dynamic parameters

Const routes: Routes = [{path: "home", component: HomeComponent}, {path: "about/:name", component: AboutComponent}] about our import {ActivatedRoute} from "@ angular/router" export class AboutComponent implements OnInit {constructor (private route: ActivatedRoute) {} ngOnInit (): void {this.route.paramMap.subscribe (params = > {params.get ("name")})} route nesting

Route nesting refers to how child routes are defined.

Const routes: Routes = [{path: "about", component: AboutComponent, children: [{path: "introduce", component: IntroduceComponent}, {path: "history", component: HistoryComponent}]}]

About works!

Company profile Development History named socket

Display child routing components in different routing sockets

{path: "about", component: AboutComponent, children: [{path: "introduce", component: IntroduceComponent, outlet: "left"}, {path: "history", component: HistoryComponent, outlet: "right"}]}

About works!

About our navigation route to the development history / / app.component.tsimport {Router} from "@ angular/router" export class HomeComponent {constructor (private router: Router) {} jump () {this.router.navigate (["/ about/history"], {queryParams: {name: "Kitty"})} routing module

Abstract the routing configuration in the root module into a separate routing module, which is called the root routing module, and then introduce the root routing module into the root module.

Import {NgModule} from "@ angular/core" import {HomeComponent} from ". / pages/home/home.component" import {NotFoundComponent} from ". / pages/not-found/not-found.component" const routes: Routes = [{path: ", component: HomeComponent}, {path:" * * ", component: NotFoundComponent}] @ NgModule ({declarations: [], imports: [RouterModule.forRoot (routes, {useHash: true})] / / Export Angular routing function module Because the routing socket component provided in the root module exports: [RouterModule]}) export class AppRoutingModule {} import {BrowserModule} from "@ angular/platform-browser" import {NgModule} from "@ angular/core" import {AppComponent} from ". / app.component" import {AppRoutingModule} from ". / app-routing.module" @ NgModule ({declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [] Bootstrap: [AppComponent]}) export class AppModule {} routing lazy load

Routing lazy loading is based on modules.

Create the user module ng g m user-routing=true and create the routing module for this module

Create login page component ng g c user/pages/login

Create a registration page component ng g c user/pages/register

Configure routing rules for the user module

Import {NgModule} from "@ angular/core" import {Routes, RouterModule} from "@ angular/router" import {LoginComponent} from ". / pages/login/login.component" import {RegisterComponent} from ". / pages/register/register.component" const routes: Routes = [{path: "login", component: LoginComponent}, {path: "register", component: RegisterComponent}] @ NgModule ({imports: [RouterModule.forChild (routes)], exports: [RouterModule]}) export class UserRoutingModule {}

Associate the user routing module to the primary routing module

/ / app-routing.module.tsconst routes: Routes = [{path: "user", loadChildren: () = > import (". / user/user.module") .then (m = > m.UserModule)}]

Add an access link to the navigation component

Log in to the registered routing guard

The route guard tells the route whether it is allowed to navigate to the requested route.

Routing methods can return boolean or Observable\ or Promise\, which are resolved to Boolean values at some point in the future

1 、 CanActivate

Check to see if the user can access a route.

CanActivate is the interface. To implement this interface, the routing guard class specifies that the canActivate method is required in the class, and the method determines whether the destination route is allowed to be accessed.

Multiple guards can be applied to the route, and all guard methods are allowed before the route is allowed to be accessed. If one guard method is not allowed, the route is not allowed to be accessed.

Create routing Guard: ng g guard guards/auth

Import {Injectable} from "@ angular/core" import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree Router} from "@ angular/router" import {Observable} from "rxjs" @ Injectable ({providedIn: "root"}) export class AuthGuard implements CanActivate {constructor (private router: Router) {} canActivate (): boolean | UrlTree {/ / is used to redirect return this.router.createUrlTree (["/ user/login"]) / / disable access to the destination route return false / / allow access to the destination route return true} {path: "about" Component: AboutComponent, canActivate: [AuthGuard]}

2 、 CanActivateChild

Check to see if the user can access a child route.

Create routing Guard: ng g guard guards/admin

Note: to select CanActivateChild, you need to move the arrow to this option and click the space to confirm the selection

Import {Injectable} from "@ angular/core" import {CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree} from "@ angular/router" import {Observable} from "rxjs" @ Injectable ({providedIn: "root"}) export class AdminGuard implements CanActivateChild {canActivateChild (): boolean | UrlTree {return true}} {path: "about", component: AboutComponent, canActivateChild: [AdminGuard], children: [{path: "introduce", component: IntroduceComponent}]}

3 、 CanDeactivate

Check whether the user can exit the route. For example, if the user's input in the form is not saved and the user wants to leave the route, the guard can be called to prompt the user.

Import {Injectable} from "@ angular/core" import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree} from "@ angular/router" import {Observable} from "rxjs" export interface CanComponentLeave {canLeave: () = > boolean} @ Injectable ({providedIn: "root"}) export class UnsaveGuard implements CanDeactivate {canDeactivate (component: CanComponentLeave): boolean {if (component.canLeave ()) {return true} return false} {path: ", component: HomeComponent CanDeactivate: [UnsaveGuard]} import {CanComponentLeave} from "src/app/guards/unsave.guard" export class HomeComponent implements CanComponentLeave {myForm: FormGroup = new FormGroup ({username: new FormControl ()}) canLeave (): boolean {if (this.myForm.dirty) {if (window.confirm ("No data has not been saved, are you sure you want to leave") {return true} else {return false} return true}

4 、 Resolve

Allow you to get the data before entering the route, and then enter the route after the data acquisition is completed.

$ng g resolver import {Injectable} from "@ angular/core" import {Resolve} from "@ angular/router" type returnType = Promise@Injectable ({providedIn: "root"}) export class ResolveGuard implements Resolve {resolve (): returnType {return new Promise (function (resolve) {setTimeout () = > {resolve ({name: "Zhang San")}, 2000)}} {path: ", component: HomeComponent" Resolve: {user: ResolveGuard}} export class HomeComponent {constructor (private route: ActivatedRoute) {} ngOnInit (): void {console.log (this.route.snapshot.data.user)}} on how to understand routes in Angular, that's all. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report