1. 程式人生 > >Angular4.x通過路由守衛進行路由重定向,實現根據條件跳轉到相應的頁面

Angular4.x通過路由守衛進行路由重定向,實現根據條件跳轉到相應的頁面

spl date() 個人 document ons n) ID exp nav

需求:

最近在做一個網上商城的項目,技術用的是Angular4.x。有一個很常見的需求是:用戶在點擊“我的”按鈕時讀取cookie,如果有數據,則跳轉到個人信息頁面,否則跳轉到註冊或登錄頁面

解決

在這裏通過Angular的路由守衛來實現該功能。

1. 配置路由信息

const routes = [
  { path: 'home', component: HomeComponent },
  { path: 'product', component: ProductComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'my', component: MyComponent },
  { path: 'login', component: LoginComponent, canActivate: [RouteguardService] },//canActivate就是路由守衛
  { path: '', redirectTo: '/home', pathMatch: 'full' }
]

2. 路由守衛條件(RouteguardService.ts)

import { Injectable, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, NavigationStart } from "@angular/router";
import userModel from "./user.model";

@Injectable()
export class RouteguardService implements CanActivate {
    constructor(private router: Router, @Inject(DOCUMENT) private document: any) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        // this.setCookie("userId", "18734132326", 10);
        //讀取cookie
        var cookies = this.document.cookie.split(";");
        var userInfo = { userId: "", pw: "" };
        if (cookies.length > 0) {
            for (var cookie of cookies) {
                if (cookie.indexOf("userId=") > -1) {
                    userModel.accout = cookie.split("=")[0];
                    userModel.password = cookie.split("=")[1];
                    userModel.isLogin = false;
                }
            }
        }

        //獲取當前路由配置信息
        var path = route.routeConfig.path;
        if (path == "login") {
            if (!userModel.isLogin) {
                //讀取cookie如果沒有用戶信息,則跳轉到當前登錄頁
                return true;
            } else {
                //如果已經登錄了則跳轉到個人信息頁面,下面語句是通過ts進行路由導航的
                this.router.navigate(['product'])
            }
        }

    }

    setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }
}

Angular4.x通過路由守衛進行路由重定向,實現根據條件跳轉到相應的頁面