zoukankan      html  css  js  c++  java
  • angular4.0 路由守卫详解

    在企业应用中权限、复杂页多路由数据处理、进入与离开路由数据处理这些是非常常见的需求。

    当希望用户离开一个正常编辑页时,要中断并提醒用户是否真的要离开时,如果在Angular中应该怎么做呢?

    其实Angular路由守卫属性可以帮我们做更多有意义的事,而且非常简单。

    Angular 的 Route 路由参数中除了熟悉的 pathcomponent 外,还包括四种是否允许路由激活与离开的属性。

    • canActivate: 控制是否允许进入路由。
    • canActivateChild: 等同 canActivate,只不过针对是所有子路由。
    • canDeactivate: 控制是否允许离开路由。
    • canLoad: 控制是否允许延迟加载整个模块。

    这里我们只讲canActivate的用法

    注册RouteguardService服务

    代码如下,这个是完整的守卫逻辑;每一步都写好了注释,我就不细说了,看注释就明白了;

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Router } from "@angular/router";
    import userModel from '../model/user.model';
    @Injectable()
    export class RouteguardService implements CanActivate{
    
      constructor(
        private router: Router
      ) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{
        // 返回值 true: 跳转到当前路由 false: 不跳转到当前路由
        // 当前路由名称
        var path = route.routeConfig.path;  
        // nextRoute: 设置需要路由守卫的路由集合
        const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
        let isLogin = userModel.isLogin;  // 是否登录
        // 当前路由是nextRoute指定页时
        if (nextRoute.indexOf(path) >= 0) {
          if (!isLogin) {
            // 未登录,跳转到login
            this.router.navigate(['login']);
            return false;
          }else{
            // 已登录,跳转到当前路由
            return true;
          }
        }
        // 当前路由是login时 
        if (path === 'login') {
          if (!isLogin) {
            // 未登录,跳转到当前路由
            return true;
          }else{
            // 已登录,跳转到home
            this.router.navigate(['home']);
            return false;
          }
        }
      }
    
    }

    上面的代码中,有这句代码:import userModel from '../model/user.model';

    user.model用来记录用户的状态值以及其他属性,代码如下

    let userModel = {
      isLogin: false, // 判断是否登录
      accout: '',
      password: '',
    };
    
    export default userModel;

    在app-routing.module.ts中配置路由守卫

    首先注入RouteguardService服务,然后在需要守卫的路由配置中加入:canActivate: [RouteguardService]

    这样在写有canActivate的路由中,都会调用RouteguardService服务,代码如下:

    import {NgModule} from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import {HomeComponent} from "./page/home/home.component";
    import {GoodDetailComponent} from "./page/good-detail/good-detail.component";
    import {CartComponent} from "./page/cart/cart.component";
    import {ProfileComponent} from "./page/profile/profile.component";
    import {GoodListComponent} from "./page/good-list/good-list.component";
    import { RouteguardService } from './service/routeguard.service';
    import { LoginComponent } from './page/login/login.component';
    
    const routes: Routes = [
      {
        path: '',   // 初始路由重定向[写在第一个]
        redirectTo: 'home',
        pathMatch: 'full'  // 必须要设置
      },
      {
        path: 'login',
        component: LoginComponent,
        canActivate: [RouteguardService]
      },
      {
        path: 'home',
        component: HomeComponent,
        canActivate: [RouteguardService]
      },
      {
        path: 'good-detail',
        component: GoodDetailComponent,
        canActivate: [RouteguardService]
      },
      {
        path: 'good-list',
        component: GoodListComponent,
        canActivate: [RouteguardService]
      },
      {
        path: 'cart',
        component: CartComponent,
        canActivate: [RouteguardService]
      },
      {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [RouteguardService]
      },
      {
        path: '**',   // 错误路由重定向[写在最后一个]
        redirectTo: 'home',
        pathMatch: 'full'  // 必须要设置
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

    ok,工作量还挺大的,大家慢慢研究吧

  • 相关阅读:
    angularjs1.6.4中使用ng-table出现data.slice is not a function的问题
    使用sql语句获取数据库表的信息
    IIS部署web,字体404的问题
    SQL中partition关键字的使用
    asp.net 配置二级域名的共享session,并实现sso单点登录
    同一浏览器中同一JavaWeb程序不共享session方法
    Liquibase的使用
    对象并不一定都是在堆上分配内存的
    阿里面试题,为什么wait()方法要放在同步块中?
    粗浅看 Tomcat系统架构分析
  • 原文地址:https://www.cnblogs.com/minigrasshopper/p/8028861.html
Copyright © 2011-2022 走看看