您好,登錄后才能下訂單哦!
這篇文章主要介紹了Angular4.x如何通過(guò)路由守衛(wèi)進(jìn)行路由重定向?qū)崿F(xiàn)根據(jù)條件跳轉(zhuǎn)到相應(yīng)的頁(yè)面,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
需求:
最近在做一個(gè)網(wǎng)上商城的項(xiàng)目,技術(shù)用的是Angular4.x。有一個(gè)很常見(jiàn)的需求是:用戶在點(diǎn)擊“我的”按鈕時(shí)讀取cookie,如果有數(shù)據(jù),則跳轉(zhuǎn)到個(gè)人信息頁(yè)面,否則跳轉(zhuǎn)到注冊(cè)或登錄頁(yè)面
解決
在這里通過(guò)Angular的路由守衛(wèi)來(lá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如果沒(méi)有用戶信息,則跳轉(zhuǎn)到當(dāng)前登錄頁(yè) return true; } else { //如果已經(jīng)登錄了則跳轉(zhuǎn)到個(gè)人信息頁(yè)面,下面語(yǔ)句是通過(guò)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; } }
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Angular4.x如何通過(guò)路由守衛(wèi)進(jìn)行路由重定向?qū)崿F(xiàn)根據(jù)條件跳轉(zhuǎn)到相應(yīng)的頁(yè)面”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。