码迷,mamicode.com
首页 > 其他好文 > 详细

Angular4 路由守卫

时间:2017-12-20 20:08:13      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:load   states   分层   oid   inject   private   rate   路径   cat   

序言

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

步骤

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)

 

Angular4 路由守卫

标签:load   states   分层   oid   inject   private   rate   路径   cat   

原文地址:http://www.cnblogs.com/leijing0607/p/8075324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!