您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 贵港分类信息网,免费分类信息发布

Angular4.x通过路由守卫实现动态跳转界面步骤详解

2024/3/6 10:54:55发布13次查看
这次给大家带来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;   } }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
react怎样在react-router路由实现登陆验证控制
angular路由内路由守卫该如何使用
以上就是angular4.x通过路由守卫实现动态跳转界面步骤详解的详细内容。
贵港分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录