我有以下路线-
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 });
}
关于javascript - Angular 路由器如何从父组件调用子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283560/