2016-06-30 101 views
25

我正在尝试使用路由和查询参数组合导航到Angular 2中的路由。Angular 2 router.navigate

下面是一个例子,途径的路径是路径的最后一部分:

{ path: ':foo/:bar/:baz/page', component: AComponent } 

试图使用链接的阵列,像这样:

this.router.navigate(['foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams) 

我没有得到任何错误并从我能理解这应该工作。

的角2个文档(目前)有以下为例:

{ path: 'hero/:id', component: HeroDetailComponent } 

['/hero', hero.id] // { 15 } 

任何人都可以看到我要去哪里错了吗?我在路由器3上。

回答

46

如果第一个段没有以/开头,那么它是相对路径。 router.navigate需要relativeTo参数相对导航

要么你做的绝对路径:

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}) 

又见

+1

知道这个线程是旧的 - 但一对夫妇对我的理解简单的问题:1。 在上面不应该在第二种情况”它是 'this.router.navigate(** ['foo ** - content','bar-contents',....' (没有/在第一个段的开始,因为它是相对的) 2.除了this.currentActivatedRoute relativeTo的其他可能值是什么? – Vikas

+0

如果你想要它是相对的,那么省略前面的'/',我不打算这样做。任何你想要的路径都是相对的。 –

+1

谢谢 - 但在你的回复中你已经提到过,如果第一部分以/开始,那么它是绝对导航。那么为什么需要relativeTo? – Vikas

5

import { ActivatedRoute } from '@angular/router'; 
 

 
export class ClassName { 
 
    
 
    private router = ActivatedRoute; 
 

 
    constructor(r: ActivatedRoute) { 
 
     this.router =r; 
 
    } 
 

 
onSuccess() { 
 
    this.router.navigate(['/user_invitation'], 
 
     {queryParams: {email: loginEmail, code: userCode}}); 
 
} 
 

 
} 
 

 

 
Get this values: 
 
--------------- 
 

 
ngOnInit() { 
 
    this.route 
 
     .queryParams 
 
     .subscribe(params => { 
 
      let code = params['code']; 
 
      let userEmail = params['email']; 
 
     }); 
 
}

编号:https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html