路由守卫

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yanwenwennihao/article/details/84205432

路由守卫

为什么设置路由守卫?

在不设置路由守卫的时候,任何用户都能在任何时候导航到任何地方,但是在某些场景为了安全,我们需要登陆的yoghurt才能导航到对应的页面,这时候们需要给组件添加路由守卫

 

分层路由介绍

  • CanActivate:处理导航到某路由的情况
  • CanActivateChild 处理导航到某子路由的情况
  • CanDeactivate:处理从当前路由离开的情况
  • Resolve:在路由激活之前获得路由数据
  • CanLoad :处理异步导航到某特性木块的情况

 

 

只有用户已经登陆或者拥有某些权限才可进入的路由

canActive

1.写一个守卫类,继承 CanActivate 接口

import {CanActivate} from '@angular/router';
export class LoginGuard implements CanActivate {
canActivate() {
  let loginedIn: boolean = Math.random() < 0.5;
    if (!loginedIn) {
      console.log('用户未登陆');
    }
    return loginedIn;
  }
}

这是CanDeactivate 与canActivate不同的是它要离开某个组件就需要保护那个组件,建立也要注入那个组件

 

export class UnsaveGuard implements CanDeactivate<ProductComponent>{
canDeactivate (component: ProductComponent) {
  return window.confirm('是否离开');
}

这两个返回都应该是boolean型

2.在路由配置里加配置

canActivate 在路由配置时可以配置一个数组,angular会一次调用数组中的项,一旦某个返回false,则会终止登陆操作

{
path: 'product',
component: ProductComponent,
canActivate: [loginGuard],
canDeactivate: [UnsaveGuard]
}

服务里加上该服务

@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [LoginGuard, UnsaveGuard],
exports: [RouterModule]
})

 

猜你喜欢

转载自blog.csdn.net/yanwenwennihao/article/details/84205432