angular路由守卫

266 阅读1分钟

守卫总览表

守卫功能作用范围
CanActivate导航某路由的情况可以配置在父/子路由中
CanActivateChild导航某子路由的情况只能配置父路由中
CanDeactivate从当前路由离开的情况只能配置子路由中
Resolve路由激活前获取路由数据可以配置在父/子路由中
CanLoad异步导航到某特性模块(懒加载);该api被遗弃了,使用CanMatch代替了可以配置在父/子路由中
  • canActivate(只有在刷新页面时才会触发。正常的链接跳转都不会触发)
    //canActivate配置父路由中 
    //canActivate只有在刷新页面时才会触发。正常的链接跳转都不会触发
    const routes: Routes = [ 
        { 
            path: 'parent', 
            canActivate: [canActivate],
            children: [ 
                // 子路由配置
            ] 
        } 
    ];
    
    • 如何解决上面的方案;
    • 方案一:在每个子路由都进行配置
    const routes: Routes = [ 
        { 
            path: 'parent',
            children: [ 
                { path: 'child1', canActivate: [canActivate] },
                { path: 'child2', canActivate: [canActivate] }
            ] 
        } 
    ];
    
    • 方案二:AppComponent中监听路由事件
    import { Component } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    @Component({ 
        selector: 'app-root',
        template: '<router-outlet></router-outlet>'
    }) 
    export class AppComponent { 
        constructor(private router: Router) { 
            this.router.events.subscribe(event => { 
                if (event instanceof NavigationEnd) { 
                    console.log('NavigationEnd event occurred'); 
                    // 在这里可以添加其他逻辑 
                } 
            }); 
        } 
    }
    
  • canActivateChild
//canActivateChild配置父路由中 
//canActivateChild会被调用两次。一次是在检查路由是否可以激活时,另一次是在检查子路由是否可以激活时。
const routes: Routes = [ 
    { 
        path: 'parent', 
        canActivateChild: [canActivateChild],
        children: [ 
            // 子路由配置
        ] 
    } 
];

执行顺序

  • 同一个数组按顺序执行
  • 四个守卫执行顺序?