绝对路径路由
有两种导航方法,.navigate()和.navigateByUrl()
你可以使用.navigateByUrl()方法进行绝对路径路由:
import {Router} from '@angular/router';
constructor(private router: Router) {}
navigateToLogin() {
this.router.navigateByUrl('/login');
}
将绝对路径放入要导航到的组件的URL。
注意:在调用路由器的navigateByUrl方法时,总是指定完整的绝对路径。绝对路径必须以/开头
// Absolute route - Goes up to root level
this.router.navigate(['/root/child/child']);
// Absolute route - Goes up to root level with route params
this.router.navigate(['/root/child', crisis.id]);
相对路径路由
如果您想使用相对路径路由,请使用.navigate()方法。
注意:路由的工作方式有点不直观,特别是父路由、兄弟路由和子路由:
// Parent route - Goes up one level
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });
// Sibling route - Stays at the current level and moves laterally,
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });
// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });
// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });
// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'.
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });
或者,如果你只需要在当前路由路径中导航,但指向不同的路由参数:
// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });
链路参数数组
一个链接参数数组包含以下元素用于路由器导航:
到目标组件的路由路径。(' /英雄')
进入路由URL的必需和可选路由参数。[/英雄,英雄。Id]或['/hero', {Id: hero。Id, foo: baa}]
目录式的语法
路由器在链接参数列表中支持类似目录的语法,以帮助指导路由名称查找:
./或没有前导斜杠相对于当前级别。
../在路由路径上上升一层。
可以将相对导航语法与祖先路径结合使用。如果你必须导航到兄弟路由,你可以使用../<sibling>约定向上一层,然后沿着兄弟路由路径向下。
关于相对否定的重要注意事项
使用路由器导航相对路径。方法,你必须提供ActivatedRoute来让路由器知道你在当前路由树中的位置。
在链接参数数组之后,添加一个带有relativeTo属性的对象到ActivatedRoute。路由器然后根据活动路由的位置计算目标URL。
来自Angular路由器官方文档