简体   繁体   English

如何使用activatedRoute从子组件获取父路由参数?

[英]How can I get a parent route params from a child component using activatedRoute?

I am working with a child component and I am having trouble getting access (I think) to it's parent route params.我正在使用一个子组件,并且无法访问(我认为)它的父路由参数。

My url looks like this:我的 url 看起来像这样:

/settings/organizations/26ee00d1-9fd8-4e38-a195-024c11ae0958/locations/914adefe-6b08-4f7a-9e3e-fa671a52fd3c/resources

Here is what my route(s) look like:这是我的路线的样子:

// routes.ts

path: 'settings/organizations/:organizationId/locations/:locationId',
component: LocationSettingsSummaryComponent,
children: [
    {
        path: '',
        component: LocationSettingsComponent,
    },
    {
       path: 'resources',
       component: ResourcesSummaryComponent,
    },
]

Here is what my child component looks like:这是我的子组件的样子:

// resources-summary.commponent.ts

...

organizationId!: string;
locationId!: string;

constructor(
    ...
    private readonly activatedRoute: ActivatedRoute
) {}


ngOnInit(): void {
    this.organizationId = this.activatedRoute.snapshot.paramMap.get('organizationId');
    this.locationId = this.activatedRoute.snapshot.paramMap.get('locationId')';

    console.log(this.activatedRoute.snapshot.params); // {}
}

In other components, I have been able to get to an organiationId via:在其他组件中,我可以通过以下方式访问organiationId

this.activatedRoute.snapshot.paramMap.get('organizationId')

For example, getting location details, I'm able to use this url and get the apropreate parameters例如,获取位置详细信息,我可以使用这个 url 并获取适当的参数

/settings/organizations/26ee00d1-9fd8-4e38-a195-024c11ae0958/locations/914adefe-6b08-4f7a-9e3e-fa671a52fd3c


this.locationId = this.activatedRoute.snapshot.paramMap.get('locationId')'; // 914adefe-6b08-4f7a-9e3e-fa671a52fd3c

I have tried various methods of getting the parent:我尝试了各种获取父母的方法:

console.log(this.activatedRoute.parent?.params); // {}

But that too seems to always be empty, or an empty object.但这似乎也总是空的,或者是空的 object。

I found it interesting that from my component if I do this:如果我这样做,我发现从我的组件中很有趣:

console.log(this.activatedRoute.snapshot); // resources

It seems like Angular is having trouble finding the parent?似乎 Angular 无法找到父级?

In this component, the activatedRoute params seem to always be empty.在这个组件中, activatedRoute参数似乎总是空的。 How can I get access to the route params from this child component?如何从此子组件访问路由参数?

You can get the paramMap from the parent of the ActivatedRoute like the following:您可以从ActivatedRoute的父级获取paramMap ,如下所示:

const parentParamMap = this.activatedRoute.parent.snapshot.paramMap;
const organizationId = parentParamMap.get('organizationId');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM