查看: 64|回复: 0

Angular 多重路由

[复制链接]

4

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-5-19
发表于 2021-4-18 22:40:00 | 显示全部楼层 |阅读模式

文中使用的工具或者包的版本:Angular CLI 11.0.6

文中 Demo 链接:https://stackblitz.com/edit/angular-route-outlet-3crvst

配置

首先我们在模板中定义多个路由出口,比如:

<router-outlet></router-outlet>
<router-outlet name="second"></router-outlet>
<router-outlet name="third"></router-outlet>

注意路由出口的名称不能动态设置或更改。如果未设置,则默认值为 “primary”。

然后我们给每个路由出口配置对应的路由,比如:

const routes: Routes = [
  { path: "route1", component: Route1Component },
  { path: "route2", component: Route2Component },
  { path: "secondRoute1", component: SecondRoute1Component, outlet: "second" },
  { path: "secondRoute2", component: SecondRoute2Component, outlet: "second" },
  { path: "thirdRoute1", component: ThirdRoute1Component, outlet: "third" },
];

其中 outlet 属性用于标识目标出口。

激活

现在我们可以在 outlets 中为对应的路由出口指定目标路由,指定为 null 时可关闭路由视图,比如:

<a [routerLink]="[{outlets: { second: 'secondRoute1' }}]">second:secondRoute1</a>
<a [routerLink]="[{outlets: { second: 'secondRoute2' }}]">second:secondRoute2</a>
<a [routerLink]="[{outlets: { second: null }}]">second:null</a>

多重路由之间彼此互不依赖,上面的链接会改变 second 出口的路由视图,但主路由出口和 third 路由出口不受影响。除了动态路径,我们也可以用跳转到对应的 URL 的方法来激活它们。

URL

多重路由在 URL 的表现上由括号包装,比如:http://localhost:4200/route2(second:secondRoute1)。同一模板上有多个路由出口被激活时,URL 中以 // 分隔,父子路由上都有多重路由时就会出现多个括号包装的内容。在使用 URL 激活路由时要注意会不会弄丢其他路由出口的路由视图,正确的代码应该像这样:

this.router.navigateByUrl("/route2(second:secondRoute1)");
this.router.navigateByUrl("/route1/(childRoute1//second:childSecondRoute1)(second:secondRoute1//third:thirdRoute1)");


来源:https://www.cnblogs.com/yshenhua/p/14674960.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部