Table of Contents
Route Guards
Summary
Home Web Front-end JS Tutorial A brief analysis of Angular learning route by Route Guards

A brief analysis of Angular learning route by Route Guards

Nov 04, 2021 am 10:14 AM
angular route guard

This article will take you to learn about Route Guards in Angular, and introduce the methods of creating route guards, controlling whether routes can be activated, and controlling whether routes can be exited. I hope it will be helpful to everyone!

A brief analysis of Angular learning route by Route Guards

Environment:

  • Angular CLI: 11.0.6

  • Angular: 11.0.7

  • Node: 12.18.3

  • npm : 6.14.6

  • IDE: Visual Studio Code

In our actual business development process, we often encounter the following requirements:

  • It is necessary to restrict the accessibility of certain URLs. For example, for the system management interface, only those users with administrator rights can open it. [Related tutorial recommendation: "angular tutorial"]

  • When the user is in the editing interface and leaves without saving, the user needs to be prompted whether to abandon the modification.

For the above scenario, Angualr uses Route Guards (Route Guards) to implement.

Route Guards

1. Create a route guard

Angular CLI provides a command line tool that can Quickly create a routing guard framework file: ng generate guard auth. After execution, Angular CLI will ask us which interfaces we need to implement, we can just check it directly:

? Which interfaces would you like to implement? (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) CanActivate
 ( ) CanActivateChild
 ( ) CanDeactivate
 ( ) CanLoad
Copy after login

Description:

  • CanActivate: Controls whether the route can be activated

  • CanActivateChild: Controls whether the sub-route can be activated

  • CanDeactivate: Controls whether the route can exit

  • CanLoad : Control whether the module can be loaded

The more commonly used ones are 1 and 3, which control entry and exit respectively. According to the above configuration, AngularCLI automatically generates the following code, return true; can be replaced with our actual code. return false; Indicates that jumping is not allowed or canceling leaving the current page.

// auth.guard.ts
import { Injectable } from &#39;@angular/core&#39;;
import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from &#39;@angular/router&#39;;
import { Observable } from &#39;rxjs&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class AuthGuard implements CanActivate, CanDeactivate<unknown> {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return true;
  }
}
Copy after login

In the canActivate method, we can also use jumps. For example, the page determines whether you have logged in. If you are not logged in, jump to the Login page:

this.router.navigate([&#39;/login&#39;]);
return false;
Copy after login

2. Control whether routing can be activated

Control Whether the route can be activated needs to be defined where the route is defined and the canActivate attribute is added. If necessary, you can also add data attributes, such as telling our AuthGuard which permissions need to be verified to enter the current route. The data attribute is optional.

const routes: Routes = [
  {
    path: "page1",
    component: Page1Component,
    data: { permissions: [&#39;YourPage1Permission&#39;] },  // 传入参数给AuthGuard,可选
    canActivate: [AuthGuard]
  },
  {
    path: "page2",
    component: Page2omponent,
    data: { permissions: [&#39;YourPage2Permission&#39;] },  // 传入参数给AuthGuard,可选
    canActivate: [AuthGuard]
  }
]
Copy after login

3. Control whether the route exits (leave)

is similar to controlling whether the route can be activated. Add to the route definition. canDeactivate, and formulate the corresponding Guard guard. No more examples here

Summary

  • Control the entry and exit of URLs through Route Guards;

  • Angular CLI can assist us in creating guard files;

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of A brief analysis of Angular learning route by Route Guards. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

Let's talk about how to customize the angular-datetime-picker format Let's talk about how to customize the angular-datetime-picker format Sep 08, 2022 pm 08:29 PM

How to customize the angular-datetime-picker format? The following article talks about how to customize the format. I hope it will be helpful to everyone!

See all articles