需求:
最近在做一个网上商城的项目,技术用的是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通过路由守卫进行路由重定向实现根据条件跳转到相应的页面,希望对大家有所帮助
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论