這次帶給大家Angular4.x透過路由守衛進行路由重定向步驟詳解,Angular4.x透過路由守衛進行路由重定向的注意事項有哪些,下面就是實戰案例,一起來看一下。
需求:
最近在做一個網路商城的項目,技術用的是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; } }
# 相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是Angular4.x透過路由守衛進行路由重定向步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!