守卫总览表
| 守卫 | 功能 | 作用范围 |
|---|
| CanActivate | 导航到某路由的情况 | 可以配置在父/子路由中 |
| CanActivateChild | 导航到某子路由的情况 | 只能配置父路由中 |
| CanDeactivate | 从当前路由离开的情况 | 只能配置子路由中 |
| Resolve | 路由激活前获取路由数据 | 可以配置在父/子路由中 |
CanLoad | 异步导航到某特性模块(懒加载);该api被遗弃了,使用CanMatch代替了 | 可以配置在父/子路由中 |
- canActivate(只有在刷新页面时才会触发。正常的链接跳转都不会触发)
const routes: Routes = [
{
path: 'parent',
canActivate: [canActivate],
children: [
]
}
];
- 如何解决上面的方案;
- 方案一:在每个子路由都进行配置
const routes: Routes = [
{
path: 'parent',
children: [
{ path: 'child1', canActivate: [canActivate] },
{ path: 'child2', canActivate: [canActivate] }
]
}
];
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
const routes: Routes = [
{
path: 'parent',
canActivateChild: [canActivateChild],
children: [
]
}
];
执行顺序