Home  >  Article  >  Web Front-end  >  A brief discussion on the usage of routing guards in angular9

A brief discussion on the usage of routing guards in angular9

青灯夜游
青灯夜游forward
2021-03-18 09:49:282386browse

This article will introduce to you the use of Angularrouting guards. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the usage of routing guards in angular9

What is Route Guard

Any user can navigate to anywhere at any time. But sometimes you need to control access to different parts of the application for various reasons. Possible scenarios include the following:

The user may not have permission to navigate to the target component.

Maybe the user must log in (authentication) first.

You may have to obtain some data before displaying the target component.

You may want to save changes before leaving the component.

You may want to ask the user: Do you want to discard this change without saving them?

Related recommendations: "angular tutorial"

Creation of components

1. Home component Create
2. Login component creation
3. First and second sub-components under home

A brief discussion on the usage of routing guards in angular9

Guard routing related core code

Every route in routing is open to everyone. These new management features should only be accessible to logged-in users.

Write a CanActivate() guard to redirect anonymous users who are trying to access the management component to the login page.

1.1 In the auth folder, create a new auth.service.ts file to simulate the login request service. The actual scenario is generally to save the background token in a cookie.

import { Injectable } from '@angular/core';

import { Observable, of } from 'rxjs';
import { tap, delay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  isLoggedIn = false; //默认未登录

  // 记录登录之后,需要跳转到原来请求的地址
  redirectUrl: string;
// 登录
  login(): Observable<boolean> {
    return of(true).pipe(
      delay(1000),
      tap(val => this.isLoggedIn = true)
    );
  }
// 登出
  logout(): void {
    this.isLoggedIn = false;
  }
}</boolean>

1.2 In the auth folder, create a new auth.guard.ts file

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { AuthService } from './auth.service'; 
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    let url: string = state.url
    return this.checkLogin(url);
  }
  
  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // 保存原始的请求地址,登录后跳转到该地址
    this.authService.redirectUrl = url;

    // 未登录,跳转到登录页面
    this.router.navigate(['/login']);
    return false;
  }
}

Use guard in routing

Use

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth/auth.guard';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
 
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'home',
    loadChildren: () => import('./home/home.module')
      .then(mod => mod.HomeModule),
    canActivate: [AuthGuard], // 守卫路由
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

under the app-routing.module.ts file

General routing guards and interceptors Use them together. If you are interested, you can learn more.

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

The above is the detailed content of A brief discussion on the usage of routing guards in angular9. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete