1. 程式人生 > >Angular4 路由守衛

Angular4 路由守衛

params ogg nav eat hub 路由 sessionid arr github

序言

  在不設置路由守衛的時候,任何用戶能在任何時候導航到任何地方的,但是在某些場景為了安全,我們需要登錄的用戶才能導航到對應的頁面。這時候我們需要給組件添加路由守衛。

步驟

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 路由守衛