因为项目需要,因此开始使用主路由和辅助路由,主路由和辅助路由可以用来分别控制项目的不同部分进行跳转,例如实现左半部分和右半部分分别跳转到不同的模块,展示不同的内容。
使用
- 在项目的根模块或次级的根模块,如
mainPage.component
的html中增加主路由和辅助路由的入口
1 | <!-- 主路由 --> |
2 | <router-outlet></router-outlet> |
3 | ... |
4 | <!-- 辅助路由 --> |
5 | <router-outlet name="secondPanel"></router-outlet> |
6 | ... |
- 在该模块的路由部分分别设置主路由和辅助路由的跳转路径:
1 | const appRoutes: Routes = [ |
2 | { path: '', redirectTo: 'mainPage', pathMatch: 'full' }, |
3 | { |
4 | path: 'mainPage', |
5 | component: MainPageComponent, |
6 | canActivate: [ConfigService], // 设置路由守卫 提前加载配置数据, |
7 | resolve: { |
8 | crisis: BasicDataService // 预加载基础数据 |
9 | }, |
10 | children: [ |
11 | { |
12 | path: 'datasList',//列表页面 |
13 | component: DatasListComponent, |
14 | }, |
15 | { |
16 | path: 'content',//编辑页面 |
17 | component: DsContentComponent, |
18 | }, |
19 | { |
20 | path: 'datasDetail',//详情页面 |
21 | component: DatasDetailComponent, |
22 | }, |
23 | { |
24 | path: 'asideA',//辅助路由模块a |
25 | component: asideAComponent, |
26 | outlet: 'secondPanel' |
27 | }, |
28 | { |
29 | path: 'asideB',//辅助路由模块b |
30 | component: asideBComponent, |
31 | outlet: 'secondPanel' |
32 | }, |
33 | { |
34 | path: 'asideC',//辅助路由模块c |
35 | component: asideCComponent, |
36 | outlet: 'secondPanel' |
37 | } |
38 | { path: '', redirectTo: 'asideA', pathMatch: 'full', outlet: 'secondPanel' }, |
39 | { path: '', redirectTo: 'datasList', pathMatch: 'full' }, |
40 | ] |
41 | } |
42 | ]; |
- 在ts中使用:
- 只跳转主路由:
1 | this.router.navigate(['content'], { relativeTo: this.route }); |
2 | |
3 | this.router.navigate([{ outlets: { primary: 'content' } }], { |
4 | queryParams: { type: 'createNewData' }, |
5 | relativeTo: this.route |
6 | }); // 带参数跳转 |
- 只跳转辅助路由:
1 | this.router.navigate([{ outlets: { secondPanel: ['asideB'] } }], { relativeTo: this.route }); |
2 | |
3 | this.router.navigate([{ outlets: { leftPanel: ['asideC'] } }], { |
4 | queryParams: data.data, |
5 | relativeTo: this.route |
6 | }); // 带参数跳转 |
- 主路由辅助路由一起跳转:
1 | this.router.navigate([{ outlets: { primary: ['datasList'], leftPanel: ['asideA'] } }], { relativeTo: this.route }); |
2 | |
3 | this.router.navigate([{ outlets: { primary: ['content'], leftPanel: ['asideB'] } }], { queryParams: { type: 'accept' }, relativeTo: this.route }); // 带参数跳转 |
在html中的使用可以参考官方示例,https://stackblitz.com/angular/aeapbblxmka
1 | <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a> |
2 | <a routerLink="/superheroes" routerLinkActive="active">Heroes</a> |
3 | <a routerLink="/admin" routerLinkActive="active">Admin</a> |
4 | <a routerLink="/login" routerLinkActive="active">Login</a> |
5 | <a [routerLink]="[{ outlets: { popup: ['compose'] } }]">Contact</a> |
需要注意:如果想要主路由,辅助路由一起跳转,不可以先写一行跳转主路由,再写一行跳转辅助路由,应该只写一句navigate,实现两个路由一起跳转。
1 | ... |
2 | this.router.navigate([{ outlets: { primary: ['content']} }], { relativeTo: this.route }); |
3 | this.router.navigate([{ outlets: { leftPanel: 'asideB' } }], { relativeTo: this.route }); |
4 | ... |