【问题标题】:angular router how to call child component from the parent component角度路由器如何从父组件调用子组件
【发布时间】:2019-04-16 10:29:24
【问题描述】:

我有以下路线-

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】:

    因为navigate 接受绝对路径。

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

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

    【讨论】:

    • 我还有一个问题——在父级的构造函数中,我需要知道 url 中是否有 id,如果没有,我需要添加一个默认值。你知道我怎样才能在父母中识别出我在 url 中有 id 吗? this.route.snapshot.params.id 返回未定义。
    • 快照已弃用,请尝试this.route.params.subscribe(params => this.router.navigate(...))
    • 当我在 url 中有一个 id 时,参数也是空的,比如 - localhost:4200/parent/child。我想知道我的 url 中是否有子 ID。
    • this.route.snapshot.firstChild 有效!它可以识别父组件中的子组件。
    猜你喜欢
    • 2018-02-07
    • 2022-07-07
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2019-11-03
    • 2018-05-17
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多