角度路由器如何从父组件调用子组件

dan*_*nda 1 javascript routes typescript angular

我有以下路线-

const routes: Routes = [
    {
        path: '',
        component: ParentComponent,
        children: [
            {
                path: ':id',
                component: ChildComponent,
            },
        ]
    }
];
Run Code Online (Sandbox Code Playgroud)

在父的构造函数中,我想导航到某个 id,例如“test”。我试过这个-

constructor(private router: Router) {
    this.router.navigate(['child']);
}
Run Code Online (Sandbox Code Playgroud)

和这个-

constructor(private router: Router) {
    this.router.navigate(['/child']);
}
Run Code Online (Sandbox Code Playgroud)

和这个-

constructor(private router: Router) {
    this.router.navigate(['./child']);
}
Run Code Online (Sandbox Code Playgroud)

和这个-

constructor(private router: Router) {
        this.router.navigate(['../child']);
    }
Run Code Online (Sandbox Code Playgroud)

我的网址是 - http://localhost:4200/parent

但所有这些选项我都去http://localhost:4200/child而不是http://localhost:4200/parent/child

知道为什么吗?我怎样才能使它相对于父母?

小智 5

因为navigate采用绝对路径。

你必须明确地告诉它是相对的:

constructor(
  private router: Router,
  private route: ActivatedRoute
) {
  this.router.navigate(['child'], { relativeTo: this.route });
}
Run Code Online (Sandbox Code Playgroud)