国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:34:26
字體:
來源:轉載
供稿:網友

需求:

最近在做一個網上商城的項目,技術用的是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通過路由守衛進行路由重定向實現根據條件跳轉到相應的頁面,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 安图县| 中山市| 江陵县| 盐津县| 忻州市| 顺平县| 墨江| 广州市| 安新县| 临沂市| 广河县| 渝北区| 黔南| 太湖县| 湖南省| 蓝田县| 泽普县| 二手房| 亳州市| 和平区| 扶绥县| 安新县| 萨嘎县| 泗水县| 肃南| 长汀县| 嘉义市| 武平县| 红河县| 诸城市| 辛集市| 镶黄旗| 陆丰市| 墨竹工卡县| 鸡泽县| 鞍山市| 杭锦旗| 皮山县| 子洲县| 永泰县| 三江|