需求:
最近在做一個(gè)網(wǎng)上商城的項(xiàng)目,技術(shù)用的是Angular4.x。有一個(gè)很常見的需求是:用戶在點(diǎn)擊“我的”按鈕時(shí)讀取cookie,如果有數(shù)據(jù),則跳轉(zhuǎn)到個(gè)人信息頁面,否則跳轉(zhuǎn)到注冊或登錄頁面
解決
在這里通過Angular的路由守衛(wèi)來實(shí)現(xiàn)該功能。
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就是路由守衛(wèi) { path: '', redirectTo: '/home', pathMatch: 'full' }]
2. 路由守衛(wèi)條件(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; } } } //獲取當(dāng)前路由配置信息 var path = route.routeConfig.path; if (path == "login") { if (!userModel.isLogin) { //讀取cookie如果沒有用戶信息,則跳轉(zhuǎn)到當(dāng)前登錄頁 return true; } else { //如果已經(jīng)登錄了則跳轉(zhuǎn)到個(gè)人信息頁面,下面語句是通過ts進(jìn)行路由導(dǎo)航的 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; }}
總結(jié)
以上所述是小編給大家介紹的Angular4.x通過路由守衛(wèi)進(jìn)行路由重定向?qū)崿F(xiàn)根據(jù)條件跳轉(zhuǎn)到相應(yīng)的頁面,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注