Angular4 路由守卫

序言

  在不设置路由守卫的时候,任何用户能在任何时候导航到任何地方的,但是在某些场景为了安全,我们需要登录的用户才能导航到对应的页面。这时候我们需要给组件添加路由守卫。

步骤

1、分层路由介绍

  CanActivate:处理导航到某路由的情况

  CanActivateChild:处理导航到某子路由的情况

  CanDeactivate:处理从当前路由离开的情况

  Resolve:在路由激活之前获得路由数据

  CanLoad:处理异步导航到某特性模块的情况

2、声明

  这里的路由守卫使用与Angular-cli使用命令行ng new my-app 安装的Angular4的项目

3、路由守卫需要添加的代码(所有的文件路径与我下面的代码路径一致)

src/app/auth.service.ts

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

import { Observable } from ‘rxjs/Observable‘;
import ‘rxjs/add/observable/of‘;
import ‘rxjs/add/operator/do‘;
import ‘rxjs/add/operator/delay‘;

@Injectable()
export class AuthService {
  isLoggedIn = false;

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  login(): Observable<boolean> {
    return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
  }

  logout(): void {
    this.isLoggedIn = false;
    window.location.href="#/login";
  }
}

src/app/auth-guard.service.ts

import { Injectable }       from ‘@angular/core‘;
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild,
  NavigationExtras,
  CanLoad, Route
}                           from ‘@angular/router‘;
import { AuthService }      from ‘./auth.service‘;

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  canLoad(route: Route): boolean {
    let url = `/${route.path}`;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Create a dummy session id
    // let sessionId = 123456789;

    // Set our navigation extras object
    // that contains our global query params and fragment
    let navigationExtras: NavigationExtras = {
      // queryParams: { ‘session_id‘: sessionId },
      // fragment: ‘anchor‘
    };

    // Navigate to the login page with extras
    this.router.navigate([‘/login‘], navigationExtras);
    return false;
  }
}

src/app/can-deactivate-guard.service.ts

import { Injectable } from ‘@angular/core‘;
import { CanDeactivate } from ‘@angular/router‘;
import { Observable } from ‘rxjs/Observable‘;

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

src/app/selective-preloading-strategy.ts

import ‘rxjs/add/observable/of‘;
import { Injectable } from ‘@angular/core‘;
import { PreloadingStrategy, Route } from ‘@angular/router‘;
import { Observable } from ‘rxjs/Observable‘;

@Injectable()
export class SelectivePreloadingStrategy implements PreloadingStrategy {
  preloadedModules: string[] = [];

  preload(route: Route, load: () => Observable<any>): Observable<any> {
    if (route.data && route.data[‘preload‘]) {
      // add the route path to the preloaded module array
      this.preloadedModules.push(route.path);

      // log the route path to the console
      console.log(‘Preloaded: ‘ + route.path);

      return load();
    } else {
      return Observable.of(null);
    }
  }
}

在src/app/views/pages 下面加入四个登录有关的文件

src/app/app.module.ts中需要加入如下代码

import { LoginRoutingModule }      from ‘./views/pages/login-routing.module‘;
import { LoginComponent } from ‘./views/pages/login.component‘;

declarations: [
    LoginComponent,
  ],
imports: [
    LoginRoutingModule,
  ],

4、项目地址:https://github.com/0513Cassie/guard-git

使用说明

(1)下载

(2)进入文件目录 执行命令行npm install 或者 cnpm install

(3)http://localhost:4200/#/login   打开登录页面(用户名:Cassie,密码:888888)

时间: 2024-07-31 13:19:22

Angular4 路由守卫的相关文章

Angular4.x通过路由守卫进行路由重定向,实现根据条件跳转到相应的页面

需求: 最近在做一个网上商城的项目,技术用的是Angular4.x.有一个很常见的需求是:用户在点击"我的"按钮时读取cookie,如果有数据,则跳转到个人信息页面,否则跳转到注册或登录页面 解决 在这里通过Angular的路由守卫来实现该功能. 1. 配置路由信息 const routes = [ { path: 'home', component: HomeComponent }, { path: 'product', component: ProductComponent },

angular4.0 路由守卫详解

在企业应用中权限.复杂页多路由数据处理.进入与离开路由数据处理这些是非常常见的需求. 当希望用户离开一个正常编辑页时,要中断并提醒用户是否真的要离开时,如果在Angular中应该怎么做呢? 其实Angular路由守卫属性可以帮我们做更多有意义的事,而且非常简单. Angular 的 Route 路由参数中除了熟悉的 path.component 外,还包括四种是否允许路由激活与离开的属性. canActivate: 控制是否允许进入路由. canActivateChild: 等同 canActi

路由守卫

路由守卫 CanActivate  | 处理导航到某路由的情况-阻止或允许用户进入组件 CanDeactivate  | 处理从当前路由离开的情况-用户离开时 Resolve  | 在路由激活之前获取路由数据-在组件绑定的属性还没有被赋值时会报错,这个守卫就是解决这个问题的 CanActivate 1.需要新建一个 XX.guard.ts 文件 2.在这个.ts 文件里导入 CanActivate 模块 ... 长这样: canActivate(){}  这个方法 return true 用户就

vue的生命周期和路由守卫

组件相关钩子函数: beforeCreate.created.beforeMount.mounted.beforeUpdate.updated.beforeDestroy.destoryed 还有两个特殊的(使用keep-alive):activated.deactivated(不详述) v2.5.0+新增: errorCaptured (暂时还不知道咋用) 路由守卫: 全局&路由独享:beforeEach.beforeResolve(v2.5.0+新增).afterEach :beforeEn

nuxtjs中使用路由守卫

在vue中的路由守卫一般是来验证token失效什么的,当然也可以设置权限啦,在nuxtjs中如何使用路由守卫呢,话不多说,直接上代码 在plugins目录下简历route.js export default ({ app }) => { app.router.afterEach((to, from) => { console.log(to.path) }) } 然后在 nuxt.config.js中添加配置plugins即可 plugins: [ '@/plugins/element-ui',

Vue路由及路由守卫

1. Vue路由的添加 vue cli3添加vue-router通过命令vue  add  router export default new Router({ mode: 'history', routes: [ { path: '/', component: Main }, { path: '/login', component: Login } ] }) // app.vue <div id="app"> <router-view></router-

Vue router 全局路由守卫

记录一下全局路由守卫的使用: 方法一:定义一个数组用于检测与管理需要登录的页面,全局路由守卫配合本地存储判断是否跳转 import Vue from 'vue' import Router from 'vue-router' import store from './../store' import Home from 'components/home/home' // 主页组件 // 其它组件... import Cart from 'components/cart/cart' // 购物车组

Vue配置路由和传参方式及路由守卫!

安装路由 npm i vue-router -S 引入路由 import VueRouter form VueRouter 注入路由模块 Vue.use(VueRouter) 定义路由匹配规则 let routes = [ {...}, {...} ] 上列匹配规则中 对象有如下属性 path : 路由路径 component : 所加载的组件 name : 别名 redirect : 重定向 children : 子级路由 创建路由实例 let router = new VueRouter({

Vue-router 路由守卫

Vue-router 路由守卫 const router = new VueRouter({ ... }) 前置路由守卫 router.beforeEach((to,from,next) => { // to 下一跳路由路径地址 // from 上次路由地址对象 // next 回调钩子函数,next会解析出当前路径是否合法,是否需要路径判断重定向报错等 可以给next传参 //  执行的效果依赖传递的next 参数,如果全部钩子执行完毕,路由状态转为confirmed //  next 可接受