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;
    }
}

原文地址:https://www.cnblogs.com/xzsty/p/9015995.html

时间: 2024-07-29 21:24:17

Angular4.x通过路由守卫进行路由重定向,实现根据条件跳转到相应的页面的相关文章

angular4.0 路由守卫详解

在企业应用中权限.复杂页多路由数据处理.进入与离开路由数据处理这些是非常常见的需求. 当希望用户离开一个正常编辑页时,要中断并提醒用户是否真的要离开时,如果在Angular中应该怎么做呢? 其实Angular路由守卫属性可以帮我们做更多有意义的事,而且非常简单. Angular 的 Route 路由参数中除了熟悉的 path.component 外,还包括四种是否允许路由激活与离开的属性. canActivate: 控制是否允许进入路由. canActivateChild: 等同 canActi

angular 路由守卫

创建路由守卫 创建路由(CanActivate.CanActivateChild.CanDeactivate)守卫的命令为: ng generate guard auth/auth(自定义) 创建Resolve守卫的方式有些许不同.这个要用在一个服务中继承 1.ng generate service test-resolve 2.在生成的服务继承Resolve<T>方法,并实现.其中Person是一个类 export class TestResolverService implements R

Vue 嵌套路由、路由守卫

嵌套路由 嵌套路由:一个路由配置中嵌套其他的路由配置. 嵌套路由挺常用的,比如导航栏有首页.文章.想法.留言4个模块,我们以嵌套路由的形式集成这些模块,在导航栏中点击对应的条目,就会路由到对应的页面(下方显示对应的页面),和html的<iframe>效果差不多. demo   嵌套路由 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title><

Angular4 路由守卫

序言 在不设置路由守卫的时候,任何用户能在任何时候导航到任何地方的,但是在某些场景为了安全,我们需要登录的用户才能导航到对应的页面.这时候我们需要给组件添加路由守卫. 步骤 1.分层路由介绍 CanActivate:处理导航到某路由的情况 CanActivateChild:处理导航到某子路由的情况 CanDeactivate:处理从当前路由离开的情况 Resolve:在路由激活之前获得路由数据 CanLoad:处理异步导航到某特性模块的情况 2.声明 这里的路由守卫使用与Angular-cli使

Vue路由及路由守卫

1. Vue路由的添加 vue cli3添加vue-router通过命令vue  add  router export default new Router({ mode: 'history', routes: [ { path: '/', component: Main }, { path: '/login', component: Login } ] }) // app.vue <div id="app"> <router-view></router-

Vue配置路由和传参方式及路由守卫!

安装路由 npm i vue-router -S 引入路由 import VueRouter form VueRouter 注入路由模块 Vue.use(VueRouter) 定义路由匹配规则 let routes = [ {...}, {...} ] 上列匹配规则中 对象有如下属性 path : 路由路径 component : 所加载的组件 name : 别名 redirect : 重定向 children : 子级路由 创建路由实例 let router = new VueRouter({

Vue-router 路由守卫

Vue-router 路由守卫 const router = new VueRouter({ ... }) 前置路由守卫 router.beforeEach((to,from,next) => { // to 下一跳路由路径地址 // from 上次路由地址对象 // next 回调钩子函数,next会解析出当前路径是否合法,是否需要路径判断重定向报错等 可以给next传参 //  执行的效果依赖传递的next 参数,如果全部钩子执行完毕,路由状态转为confirmed //  next 可接受

vue2.0 实现导航守卫(路由守卫)---登录验证

路由跳转前做一些验证,比如登录验证,是网站中的普遍需求. 对此,vue-route 提供的 beforeRouteUpdate 可以方便地实现导航守卫(navigation-guards). 导航守卫(navigation-guards)这个名字,听起来怪怪的,但既然官方文档是这样翻译的,就姑且这么叫吧. 贴上文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html 全局守卫 你可以使用 router.beforeEa

路由守卫

路由守卫 CanActivate  | 处理导航到某路由的情况-阻止或允许用户进入组件 CanDeactivate  | 处理从当前路由离开的情况-用户离开时 Resolve  | 在路由激活之前获取路由数据-在组件绑定的属性还没有被赋值时会报错,这个守卫就是解决这个问题的 CanActivate 1.需要新建一个 XX.guard.ts 文件 2.在这个.ts 文件里导入 CanActivate 模块 ... 长这样: canActivate(){}  这个方法 return true 用户就