简体   繁体   English

使用参数定义路由时 angular 中的路由问题

[英]Routing issue in angular while define routing with parameter

i have two routes defined like this我有两条这样定义的路线

children: [
                            {
                                path: 'Templates', component: TemplatesComponent
                            },
                            {
                                path: 'AddEditTemplate/:id', component: AddTemplatesComponent
                            }]

I have "cancel" button on AddTemplatesComponent view我在 AddTemplatesComponent 视图上有“取消”按钮

<a class="btn btn-default no-margin" [routerLink]="['../Templates']">Cancel</a>

But clicking on cancel button it not navigate to "Templates" component and the url changed from "/AddEditTemplate/5" to "/AddEditTemplate/Templates".但是单击取消按钮它不会导航到“模板”组件,并且 url 从“/AddEditTemplate/5”更改为“/AddEditTemplate/Templates”。 But url should change to "/Templates".但是 url 应该改为“/Templates”。

What am i doing wrong?我究竟做错了什么? please help.请帮忙。

In fact you have to go up 2 routes in the path.事实上,你必须 go 路径中的 2 条路由。 For example, let's suppose you're at root/AddEditTemplate/2 .例如,假设您位于root/AddEditTemplate/2 If you go up 1 route in the path, you'll be at root/AddEditTemplate .如果你 go 在路径中向上 1 条路线,你将在root/AddEditTemplate So, to be in root again to get to root/Templates , you should go up 2 routes in the path:因此,要再次进入root以到达root/Templates ,您应该 go 路径中的 2 条路由:

<a class="btn btn-default no-margin" [routerLink]="['../../Templates']">Cancel</a>

Checkout this Stackblitz demo => focus just in the files inside module-1 folder.查看这个Stackblitz 演示=> 只关注module-1文件夹中的文件。

[UPDATE]: If you want to navigate programmatically, you can use the navigate method of the Router with 2 arguments: the same route as above and a config options containing the relativeTo attribute specifying the current route as a starting point to calculate the relative paths. [更新]:如果你想以编程方式导航,你可以使用Routernavigate方法 2 arguments:与上面相同的路由和包含relativeTo属性的配置选项,指定当前路由作为计算相对路径的起点. According to the docs : If no starting route is provided, the navigation is absolute .根据文档如果没有提供起始路线,则导航是绝对的

constructor(
  private _router: Router,
  private _activatedRoute: ActivatedRoute
) {}

...

_navigate() {
  this._router.navigate(['../../Templates'], {
    relativeTo: this._activatedRoute
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM