从父组件获取参数到子组件 [英] Get param from parent component to child component

查看:24
本文介绍了从父组件获取参数到子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近对 Angular 路由器进行了很多改动,我不知道该怎么做.

There have been so many alterations to the Angular router as of late I don't know how to go about this.

我的父组件上有一个名为eventId"的参数,位于地址栏中:

I have a param on my parent component called "eventId" which is in the address bar:

http://localhost:4200/event/1

在这种情况下,它的值为 1.

In this case it's value is 1.

这是我在路由组件中声明它的方式:

Here's how I declare it in the routing component:

{ path: 'event/:eventId', loadChildren: './event/event.module#EventModule', canActivate: [AuthGuard] },

所以我有一个子组件,它就在下面:

So I have a child component which is way down the line:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

在我的购买计划组件中,如何获取 eventId?

On my purchase plans component, how can I get the eventId?

我试过了:

import { ActivatedRoute } from '@angular/router';
export class PurchasePlansComponent implements OnInit {
  eventId: number;
  constructor(private activatedRoute: ActivatedRoute) {
    this.subscription = activatedRoute.parent.params.subscribe(
      (param: any) => {
        this.eventId = param['eventId'];
      }
    );
  }
  ngOnInit() {
    alert(this.eventId);
  }
}

但这仅在我处于此级别时才有效:

But this only works if I'm at this level:

http://localhost:4200/event/1/event-home

但如果我在这个级别,它就行不通了:

But if I'm at this level it won't work:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

推荐答案

在 Angular 5.2 版本中,有 paramsInheritanceStrategy 的新功能,可以帮助您解决现在的问题.

In Angular 5.2 release there is new feature of paramsInheritanceStrategy ,that can help you for your problems now.

您可以按如下方式使用

@NgModule({
    import :[RouterModule.forRoot(router,{paramsInheritanceStrategy :'always'})]
})

它定义了路由器如何合并从父到子的参数、数据和解析数据

It defines how the router merges params, data and resolved data from parent to child

可用选项有:

1. emptyOnly: 默认,只继承无路径或无组件的父参数

1. emptyOnly: the default , only inherits parent params for path-less or component-less

2. 始终:启用父参数的无条件继承.

2. always: enables unconditional inheritance of parent params.

在组件中,您可以按如下方式使用它:

In component you can use it as follows:

 constructor(private route: ActivatedRoute) {}

 ngOnInit() {
    this.eventId = +this.route.snapshot.paramMap.get("eventId");
  }

这篇关于从父组件获取参数到子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆