一、路由
const appRoutes: Routes = [
{ path: 'user-center', component: UserCenterComponent },
{
path: 'heroes',
children: [
component: HeroListComponent,
data: { title: 'Heroes List' }
]
},
{
path: '',
redirectTo: '/heroes',
pathMatch: 'full' //以避免路由无限匹配成功而进入死循环
},
{ path: '**', component: PageNotFoundComponent }
];
任何路由的path属性值均不能使用 / 开头
routerLink:路由导航
RouterLinkActive:路由被激活时当前元素的class
router-outlet:元素指定页面组件的加载位置
<header>
<ul>
<li><a routerLink='/user-center' routerLinkActive="active">
用户中心
</a></li>
<li><a routerLink='/goods-list' routerLinkActive="active">
商品列表
</a></li>
</ul>
</header>
<main>
<router-outlet></router-outlet>
</main>
加children属性实现路由嵌套
二、路由跳转
1.routerLink
2.this.router.navigate(动态值的方式,对象是数组)
3.this.router.navigateByUrl(传字符串)
三、路由跳转传参
1.query(search方式),即问好后面拼接
<a [routerLink]="['/goods-detail']" [queryParams]="{ id: '001'}">商品详情</a>
this.router.navigate(['/goods-detail'],{queryParams:{ id: '001' }})
2.params(动态路径传参),即参数是路径的一部分
const routes: Routes = [
{
path: 'goods-detail/:id',
component: GoodsDetailComponent
}
];
<a [routerLink]="['/goods-detail', '001']">商品详情</a>
this.router.navigate(['/user-center', '001']);
四、接收参数
1.ActivatedRoute
this.route.snapshot.params //路径参数
this.route.snapshot.queryParams //search参数
或者参数订阅获取
五、参数订阅
ngOnInit(): void {
this.route.queryParams.subscribe((queryParams) => {
this.query = queryParams
})
this.route.params.subscribe((params) => {
this.params = params
})
}
六、路由守卫
帮助控制进入和离开的钩子
创建命令:ng g guard <name> 或 ng g g <name>
1.canActivate(进入): 处理导航到某路由的情况。
接收的两个参数
ActivatedRouteSnapshot(next):相当于ActivatedRoute服务下的snapshot(参数快照)
RouterStateSnapshot(state):可通过url属性获取即将访问的路由路径
2.canActivateChild:进入子组件,使用时放在父路径上(接收参数同上)
3.CanDeactivate(离开): 处理从当前路由离开的情况。
接收的四个参数
component:当前显示页面的组件
ActivatedRouteSnapshot(currentRoute):相当于ActivatedRoute服务下的snapshot(参数快照)
RouterStateSnapshot(currentState):可通过url属性获取当前访问的路由路径
RouterStateSnapshot(nextState):可通过url属性获取即将访问的路由路径
4.canLoad(在module上使用在生效)模块异步加载
返回值return的布尔值来决定是否跳转或离开
//Resolve: 在路由激活之前获取路由数据。
5.resolve 前面几个接收的都是数组,只有它接收对象