当前位置:Gxlcms > JavaScript > Angular4.x通过路由守卫进行路由重定向实现根据条件跳转到相应的页面(推荐)

Angular4.x通过路由守卫进行路由重定向实现根据条件跳转到相应的页面(推荐)

时间:2021-07-01 10:21:17 帮助过:4人阅读

需求:

最近在做一个网上商城的项目,技术用的是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通过路由守卫进行路由重定向实现根据条件跳转到相应的页面,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行