从延迟加载的路由组件中获取父路由参数

Zze*_*Zze 16 typescript angular

我试图在延迟加载的路由组件中获取父路由参数,但是使用activatedRoute.parent.params似乎不起作用?我有一个实际工作的片段,但它涉及使用'魔术'数组索引号来检索值....

为什么会这样,是否有一个更简洁的方法,我不必检索数组值(this.activatedRoute.pathFromRoot[1])?


我有以下路径,我懒惰加载模块:

parent.route

routes:Routes = [
    {
        path: "dashboard/:id",
        component: dashboard.DashboardComponent,
        canActivate: [guard.LoggedInGuard],
        children: [
            {
                path: "my-dock",
                loadChildren: 'path/child.module#Child'
            }
        ]
    }
];
Run Code Online (Sandbox Code Playgroud)

然后在child.module我的默认组件中有以下内容:

child.component

ngOnInit() {
    this.activatedRoute.pathFromRoot[1].params.subscribe((params: Params) => {
        console.log(params); // returns {id: "123456789"}
    });

    this.activatedRoute.parent.params.subscribe((params: Params) => {
        console.log(params);  // returns {}
    });
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能this.activatedRoute.parent.params用来获得id参数?

Oka*_*kan 7

好了,您可以访问父路由器数据的父节点。在某些项目结构中似乎有些奇怪,但是如果您知道路由器的结构,则可以这样做。

 constructor(
    private route: ActivatedRoute

)
this.route.parent.parent.params.subscribe( (params) => {
        console.log(params);
        this.urlKey = params['urlKey'];
    });
Run Code Online (Sandbox Code Playgroud)


Rah*_*ngh 1

无需使用 Service 即可完成此任务的最佳方法'magic' array index number是使用 Service 。

  • 获取父级中的 Params 或 URL 并将它们放入服务中。
  • 从服务的延迟加载组件中的服务变量访问参数。像这样的事情

父组件

constructor(private router : Router){
    this.service.setParams(this.router.url);//you might need to split here
    //you can also make use of Activate Route and subcribe to params
}
Run Code Online (Sandbox Code Playgroud)

服务

params:string;

setParams(params:string){
    this.params = params;
}

getparams(){
    return this.params;
}
Run Code Online (Sandbox Code Playgroud)

现在,在子 Lazyloaded 组件中,您可以使用以下方式获取参数service.getparams()