【问题标题】:How to get params url parent id from children如何从孩子那里获取参数 url 父 ID
【发布时间】:2018-08-27 05:14:08
【问题描述】:

我的 route.ts 中有这个

 path: 'profile/:id',
                component: ProfileComponent,
                canActivate: [SiteRouteGuard],
                children: [

                    {
                        path: 'albums',
                        component: AlbumsComponent,
                        canActivate: [SiteRouteGuard]

                    },
                               ...
                         ]

现在在我的 profile.ts 我得到了这个

localhost:4200/profile/45666

当我路由到作为我 profile.ts 的子目录的 album.ts 时

localhost:4200/profile/45666/albums

现在我在我的专辑中。ts 如何获得 id 45666?

我尝试使用ActivatedRoute:

console.log(this._route.snapshot.params.id) >> undefined

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    您可以使用angular/router 中的ActivatedRoute

    import { ActivatedRoute, Router } from "@angular/router"
    
    public activatedRoute: ActivatedRoute
    
    this.activatedRoute.parent.params // return observable
    

    如果你想要静态值,那么要求

    this.activatedRoute.parent.snapshot.params // return static values
    

    通过使用属性parent,可以访问父组件的所有参数和查询

    【讨论】:

    • 里面有一个名为 _value 的对象和我需要的 id,我尝试这样做this.activatedRoute.parent.params._value.id 但未定义
    • this.activatedRoute.parent.params 返回一个 observable,如果你想要静态值,你应该询问 this.activatedRoute.parent.snaptshot.params
    【解决方案2】:

    这样做

    import { ActivatedRoute } from "@angular/router";
    let idparam = this.activatedRoute.parent.snapshot.params["idparam"]
    

    【讨论】:

      【解决方案3】:

      由于角度 5.2.x 有另一种方式来访问父参数。

      您所要做的就是将配置选项paramsInheritanceStrategy 设置为'always',如下所示:

      RouterModule.forRoot(routes, {
          paramsInheritanceStrategy: 'always'
      })
      

      使用此配置,您将可以通过原型继承访问所有祖先路由参数,因此您可以直接从激活的路由中获取它:

      this.activatedRoute.snapshot.params

      【讨论】:

        【解决方案4】:

        如果您使用的是activatedRoute,您可以在ngOnInit() 方法中获取id。喜欢

        this.activatedRoute.params.subscribe((params: Params) => {
            var id = params['id'];
          });
        

        【讨论】:

          【解决方案5】:

          你需要从@angular/router 导入ActivatedRoute:

          import { ActivatedRoute } from "@angular/router";
          

          然后在 AlbumsComponent 的构造函数中,您可以获取 :id 参数 像这样:

          let id = this.activatedRoute.parent.snapshot.params["id"]
          

          希望对你有帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-18
            • 1970-01-01
            相关资源
            最近更新 更多