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

当希望用户离开一个正常编辑页时,要中断并提醒用户是否真的要离开时,如果在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) >= ) {
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,工作量还挺大的,大家慢慢研究吧

angular4.0 路由守卫详解的更多相关文章

  1. vue2.0中router-link详解

    vue2.0中router-link详解:https://blog.csdn.net/lhjuejiang/article/details/81082090 在vue2.0中,原来的v-link指令已 ...

  2. IIS7.0 Appcmd 命令详解和定时重启应用池及站点的设置

    IIS7.0 Appcmd 命令详解 废话不说!虽然有配置界面管理器!但是做安装包的时候命令创建是必不可少的!最近使用NSIS制作安装包仔细研究了一下Appcmd的命令,可谓是功能齐全. 上网查了些资 ...

  3. loadrunner11.0 安装破解详解使用教程

    loadrunner11.0 安装破解详解使用教程 来源:互联网 作者:佚名 时间:01-21 10:25:34 [大 中 小] 很多朋友下载了loadrunner11但不是很会使用,这里简单介绍下安 ...

  4. Apache2.2+Tomcat7.0整合配置详解

    一.简单介绍 Apache.Tomcat Apache HTTP Server(简称 Apache),是 Apache 软件基金协会的一个开放源码的网页服务器,可以在 Windows.Unix.Lin ...

  5. IIS7.0 Appcmd 命令详解

    原文 IIS7.0 Appcmd 命令详解 一:准备工作 APPcmd.exe 位于 C:\Windows\System32\inetsrv 目录 使用 Cd c:\Windows\System32\ ...

  6. Android EventBus 3.0 实例使用详解

    EventBus的使用和原理在网上有很多的博客了,其中泓洋大哥和启舰写的非常非常棒,我也是跟着他们的博客学会的EventBus,因为是第一次接触并使用EventBus,所以我写的更多是如何使用,源码解 ...

  7. QuartusII13.0使用教程详解(一个完整的工程建立)

    好久都没有发布自己的博客了,因为最近学校有比赛,从参加到现在都是一脸懵逼,幸亏有bingo大神的教程,让我慢慢走上了VIP之旅,bingo大神的无私奉献精神值得我们每一个业界人士学习,向bingo致敬 ...

  8. Admin注册和路由分发详解

    Admin注册和路由分发详解 1.启动 #autodiscover_modules('admin', register_to=site) 2.注册 1.单例对象 admin.site = AdminS ...

  9. RxJava2.0的使用详解

    RxJava2.0的使用详解 1,初识RxJava RxJava就是一种用Java语言实现的响应式编程,来创建基于事件的异步程序 RxJava是一个基于事件订阅的异步执行的一个类库,目前比较火的一些技 ...

随机推荐

  1. C++如何返回不定长数组

    起初遇到这个问题的时候便得知无法返回,那么为了达到相同的目的,该怎么办呢? 第一个想法便是 int * void() { int * want = new int[size]; //......do ...

  2. 设置Eclipse的workspace路径

    首次启动Eclipse/MyEclipse时, 会弹出"Workspace Launcher"对话框, 提示设置Workspace路径. 设定好路径后, 若勾选了"Use ...

  3. HDU 1160 FatMouse's Speed (最长有序的上升子序列)

    题意:给你一系列个w,s.要你找到最长的n使得 W[m[1]] < W[m[2]] < ... < W[m[n]] and S[m[1]] > S[m[2]] > ... ...

  4. SharePoint Patterns and Practices 简介

    作者:陈希章 发表于 2017年12月22日 SharePoint Patterns and Practices,以下简称PnP,是由微软的SharePoint产品组发起并主持的一个有关SharePo ...

  5. 自学Zabbix3.8.4-可视化Visualisation-Slide shows

    Zabbix3.8.4-可视化Visualisation-Slide shows幻灯片 定义好screen之后,我们想了解服务器状况之时,一般会一个个screen点过去,zabbix提供了幻灯片展示方 ...

  6. vue中使用keepAlive组件缓存遇到的坑

    项目开发中在用户由分类页category进入detail需保存用户状态,查阅了Vue官网后,发现vue2.0提供了一个keep-alive组件. 上一篇讲了keep-alive的基本用法,现在说说遇到 ...

  7. ES6原生Promise的所有方法介绍(附一道应用场景题目)

    JS的ES6已经出来很久了,作为前端工程师如果对此还不熟悉有点说不过去.不过如果要问,Promise原生的api一共有哪几个?好像真的可以难倒一票人,包括我自己也忽略了其中一个不常用的API Prom ...

  8. iOS----------如何检查域名是否支持ipv6

    http://ipv6-test.com/validate.php  这个地址  也可以检测到! 1.检查你所用到的库,像af 3.0以上什么的(不用改),其他的库自己去搜下是否支持ipv6吧. 2. ...

  9. Python学习日记:day4

    列表 li=['alex',[1,2,3] ,'wusir','egon','女神','taibai']#列表 l1 = li[0] print(l1)#alex l2 = li[1] print ( ...

  10. python各种类型的转换

    #进制转换 ord(x) #将一个字符转换为它的整数值 hex(x) #将一个整数转换为一个十六进制字符串 oct(x) #将一个整数转换为一个八进制字符串 #类型转换int(x [,base ]) ...