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,工作量還挺大的,大家慢慢研究吧

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM