我有以下路线 -
const routes: Routes = [
{
path: '',
component: ParentComponent,
children: [
{
path: ':id',
component: ChildComponent,
},
]
}
];
在父的构造函数中,我想导航到某个id,例如'test'。我试过这个 -
constructor(private router: Router) {
this.router.navigate(['child']);
}
还有这个-
constructor(private router: Router) {
this.router.navigate(['/child']);
}
还有这个-
constructor(private router: Router) {
this.router.navigate(['./child']);
}
还有这个-
constructor(private router: Router) {
this.router.navigate(['../child']);
}
我的网址是 - http://localhost:4200/parent。
但所有这些选择我去http://localhost:4200/child而不是http://localhost:4200/parent/child
知道为什么吗?我怎样才能让它相对于父母呢?
因为navigate
采用绝对路径。
你必须明确告诉它是相对的:
constructor(
private router: Router,
private route: ActivatedRoute
) {
this.router.navigate(['child'], { relativeTo: this.route });
}