angular - Angular 2+路由器导航问题
问题描述
我正在开发一个 Angular 7 应用程序。
这是routes.module.ts文件
const routes: Routes = [{
path: '',
component: EnforcementComponent,
children: [{
path: 'orders',
children: [{
path: '',
component: OrdersComponent
},
{
path: ':id',
component: OrdersEditComponent,
}
]
}]
}];
当我在订单页面上并单击“编辑订单”按钮时,它会导航到OrdersEditComponent
所选的orderId
。
order-edit.component.ts
goToOrderDetails(order: Order) {
this.router.navigate([`home/enforcement/orders/${order.id}`]);
}
它工作正常。
但是当我直接导航到 url 时,即当我在浏览器栏上输入 -home/enforcement/orders/101
时,它会将我带回home/enforcement/orders
页面。我怎样才能解决这个问题?
请指教
解决方案
这显然取决于您的路线配置以及您将用户导航到特定路线的确切位置。
例如,如果您在订单组件中并希望将用户导航到orders/:id
路线,您可以执行以下操作:
constructor(private router: Router, private route: ActivatedRoute) {}
goToOrderDetails(order) {
this.router.navigate([`home/enforcement/orders/${order.id}`]);
}
goToOrderDetailsRelative(order) {
this.router.navigate([order.id], { relativeTo: this.route });
}
如果您要在模板中导航,您将执行以下操作:
<p>Orders Component!</p>
<button
(click)="goToOrderDetails({ id: 1 })">
Go To Order #1 Via Absolute
</button> |
<button
(click)="goToOrderDetailsRelative({ id: 1 })">
Go To Order #1 Via Relative
</button> |
<a routerLink="./1">
Go To Order #1 Via Relative Router Link
</a>
注意我们是如何在这里建立相对论的。因为用户已经在orders
路线上。
由于您应该在 order-edit 组件中执行此操作,因此您将在 TypeScript 类中像这样导航用户:
constructor(private router: Router, private route: ActivatedRoute) {}
goToOrderDetails(order) {
this.router.navigate([`home/enforcement/orders/${order.id}`]);
}
goToOrderDetailsRelative(order) {
this.router.navigate([order.id], { relativeTo: this.route.parent });
}
或者,如果您想在模板中执行此操作,您可以试试这个:
<p>Orders Edit Component!</p>
<button
(click)="goToOrderDetails({ id: 2 })">
Go To Order #2 Via Absolute
</button> |
<button
(click)="goToOrderDetailsRelative({ id: 2 })">
Go To Order #2 Via Relative
</button> |
<a routerLink="../2">
Go To Order #2 Via Relative Router Link
</a>
请仔细注意此语法与我们在订单组件中用于路由的语法之间的区别。在这两个组成部分中建立相对论的方式存在细微差别。
希望这可以帮助您更好地理解整个问题。
这是您参考的工作示例 StackBlitz。
推荐阅读
- android - kotlin android“OnbackPressed”什么都不覆盖
- excel - 将日期/时间文本字符串转换为时间格式
- r - 使用 R/examsexams2pdf() 生成 PDF 文档
- node.js - 连接到 Postgress DB 时连接被跳过
- github - 将 GitHub 问题分配给 1 人以上
- python - Django模型继承 - 如何为父属性设置值
- javascript - 如何在 Storybook + Typescript 中使用 babel-emotion-plugin?
- html - 作为 Selenium 实践的一部分,需要从下面的 HTML 中找到 SPAN 标记内的“硬件”文本
- powershell - Powershell 数据类型不兼容
- debugging - 需要帮助了解 DW_AT_ranges 值