问题描述
我正在尝试使用路由和查询参数组合导航到 Angular 2 中的路由.
I'm trying to navigate to a route in Angular 2 with a mix of route and query parameters.
这是一个示例路线,其中路线是路径的最后一部分:
Here is an example route where the route is the last part of the path:
{ path: ':foo/:bar/:baz/page', component: AComponent }
尝试使用数组进行链接,如下所示:
Attempting to link using the array like so:
this.router.navigate(['foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
我没有收到任何错误,据我所知,这应该可行.
I'm not getting any errors and from what I can understand this should work.
Angular 2 文档(目前)有以下示例:
The Angular 2 docs (at the moment) have the following as an example:
{ path: 'hero/:id', component: HeroDetailComponent }
['/hero', hero.id] // { 15 }
谁能看出我哪里出错了?我在路由器 3 上.
Can anyone see where I'm going wrong? I'm on router 3.
推荐答案
如果第一段不是以 /
开头,则它是一个相对路径.router.navigate
需要一个 relativeTo
参数来进行相对导航
If the first segment doesn't start with /
it is a relative route. router.navigate
needs a relativeTo
parameter for relative navigation
要么让路由成为绝对路径:
Either you make the route absolute:
this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
或者你通过 relativeTo
this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})
另见
- https://github.com/angular/angular.io/blob/c61d8195f3b63c3e03bf2a3c12ef2596796c741d/public/docs/_examples/router/ts/app/crisis-center.component.1.ts#L108
- https://github.com/angular/angular/issues/9476
这篇关于Angular 2 router.navigate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!