angular 路由守卫

  • 创建路由守卫

    • 创建路由(CanActivate、CanActivateChild、CanDeactivate)守卫的命令为:

      ng generate guard auth/auth(自定义)
      
    • 创建Resolve守卫的方式有些许不同。这个要用在一个服务中继承

    1、ng generate service test-resolve
    2、在生成的服务继承Resolve<T>方法,并实现。其中Person是一个类
    export class TestResolverService implements Resolve<Person> {
      constructor() { }
      resolve(route: import("@angular/router").ActivatedRouteSnapshot, state: import("@angular/router").RouterStateSnapshot):Observable<Person>{
        let p = new Person() 
        // let p:Person只是声明一个变量而已,不是定义一个变量
        p.age="sdfsdfdsdsfsad"
        p.name="fsdfsd"
        return of(p)
      }
    }
    
  • 路由守卫的使用

    • 在使用ng generate guard auth/auth在创建守卫的时候,会出现选择实现那种守卫方式的选项,按需要选者即可

    • 在auth.guard.ts中实现CanActivate,CanActivateChild

      export class AuthGuard implements CanActivate,CanActivateChild{
      
        constructor(
          private authServic:AuthService,
          private router:Router
        ){}
        canActivate(
          next: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): boolean{
          let url:string = state.url  //在跳转的时候获取
          console.log("URL:",url)
          return this.checkLogin(url);
        }
      
        checkLogin(url:string):boolean{
           // this.authServic.isLoggedIn是Boolean类型的变量
          if(this.authServic.isLoggedIn){
            return true;
          }
          console.log("checkLogin",url)
          this.router.navigate(["/login"])
          return false
        }
      
        // 子路由,用来控制子路由的被访问权限
        canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean{
          // 都只是简单的进行判断是否登录,登录之后就不会重定向到login页面
          return this.canActivate(childRoute,state)
        }  
      }
      
    • 在相对应的路由中使用。使用不同的路由守卫,在路由数组中使用不同的key进行区分(canActivate和canActivateChild)

      const routes: Routes = [
        {
          path:'admin',
          component:AdminComponent,
          canActivate:[AuthGuard],
          children:[
            {
              path:'',
              canActivateChild:[AuthGuard],
              children:[
                { path: 'crises', component: ManageCrisesComponent},
                { path: 'heroes', component: ManageHeroesComponent},
                { path: '', component: AdminDashboradComponent } 
              ]
            }
          ]
        }
      ];
      
    • 使用canDeactivate守卫,有些特殊。实例化的该方法的方法如下所示

      export class CanDeactivateGuard implements CanDeactivate<TestComponent>  {
          //CanDeactivate<T>其中T是个泛型
        canDeactivate(component: TestComponent,
           currentRoute: ActivatedRouteSnapshot, 
           currentState: RouterStateSnapshot, 
           nextState?: RouterStateSnapshot): boolean{
          return window.confirm("sdfsdfsadfsda")
        }
      }
      
    • 在路由中使用的方法于之前的类似

      const routes: Routes = [
        {
          path:'admin',
          component:AdminComponent,
          children:[
            {
              path:'',
              canActivateChild:[AuthGuard],
              children:[
                { path: 'crises', component: ManageCrisesComponent,canDeactivate:[CanDeactivateGuard] },
                { path: 'heroes', component: ManageHeroesComponent},
                { path: '', component: AdminDashboradComponent } 
              ]
            }
          ]
        }
      ];
      
    • 实例化resolve守卫。

      export class TestResolverService implements Resolve<Person> {
        constructor() { }
        resolve(route: import("@angular/router").ActivatedRouteSnapshot, state: import("@angular/router").RouterStateSnapshot):Observable<Person>{
          let p = new Person() 
          // let p:Person只是声明一个变量而已,不是定义一个变量
          p.age="sdfsdfdsdsfsad"
          p.name="fsdfsd"
          return of(p)
        }
      }
      
    • resolve守卫的使用

      const routes: Routes = [
        {
          path:'admin',
          component:AdminComponent,
          children:[
            {
              path:'',
              children:[
                { path: 'crises', component: ManageCrisesComponent},
                { path: 'heroes', component: ManageHeroesComponent,resolve:{person:TestResolverService}},  //person的标识符可以是任意符合标识符的字符串,但一般都是于该路由发送的类型名字一致的字符串
                { path: '', component: AdminDashboradComponent } 
              ]
            }
          ]
        }
      ];
      
  • 实现路由守卫的原理(CanActivate,CanActivateChild,CanDeactivate)

    • 守卫返回一个值,以控制路由器的行为
      • 如果它返回true,导航过程会继续
      • 如果他返回false,导航过程就会终止,且用户留在原地
      • 如果他返回UrlTree,则取消当前的导航,并且开始导航到返回的这个UrlTree中
  • 各个路由使用的大致场景

    • CanActivate:检查是否是登录状态访问页面;检查当前登录的用户是否权限访问这个页面(实现多角色多问题访问)
    • CanActivateChild:同上
    • CanDeactivate:当离开页面时候,修改了什么东西的时候,对用户进行访问是否保存
    • Resolve:在跳转到另一个页面的时候,先获取该页面需要的所有的值
posted @ 2019-11-30 11:59  Myuniverse  阅读(846)  评论(0编辑  收藏  举报