需求:
最近在作一個網上商城的項目,技術用的是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", "123456", 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;
}
}