angular router如何从父组件调用子组件

问题描述 投票:0回答:1

我有以下路线 -

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

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

javascript angular typescript routes
1个回答
3
投票

因为navigate采用绝对路径。

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

constructor(
  private router: Router,
  private route: ActivatedRoute
) {
  this.router.navigate(['child'], { relativeTo: this.route });
}
© www.soinside.com 2019 - 2024. All rights reserved.