I have the following route with a parameter:
RouterModule.forRoot({ path: 'record/:type', component: RecordComponent,
children: [{ path: 'edit/:id', component: RecordEditorComponent },
...] }, ...);
Inside the RecordComponent, I'm checking the type parameter and use it to set the database url to call and get the type data I need.
ngOnInit(): void {
this._route.paramMap.subscribe((parameters: ParamMap) => this.init(parameters));
...
}
private init(parameters: ParamMap): void {
this.recordType = parameters.get('type')?.toLowerCase() as RecordType | undefined;
if (!this.recordType) {
this._router.navigate(['/error', 404]);
return;
}
...
}
This works fine. But I now need a specialized NestedRecordComponent, which is derived from RecordComponent, to be used for one of the types. So I've added the route:
RouterModule.forRoot({ path: 'record/species', component: NestedRecordComponent, ... },
{ path: 'record/:type', component: RecordComponent, ... }, ...)
Now, of course, the RecordType (which is just a string enum btw.) in the url can't be found anymore. Is there a way to tell the route that species is supposed to be one of the type parameters?
I've also tried to use UrlSegments instead of type parameters, which works fine in the RecordComponent.
ngOnInit(): void {
this._route.url.subscribe((segments: UrlSegment[]) => this.init(segments));
...
}
private init(segments: UrlSegment[]): void {
this.recordType = segments.at(-1)?.path.toLowerCase() as RecordType | undefined;
...
}
However, it does not work in the child route, which also requires the type parameter, as well as the id. I've managed to pass the parent's parameters on to the child route by adding { paramsInheritanceStrategy: 'always' } to the route definitions but I have not found a way to pass on the parent's url segments, thus I would have to create two subscriptions, one for the child and one for the parent route just to get those two values, which I would really like to avoid.
Currently, the RecordEditorComponent does this, with type, of course, coming from the parent route:
ngOnInit(): void {
this._route.paramMap.subscribe((parameters: ParamMap) => this.init(parameters));
}
private init(parameters: ParamMap): void {
this._recordType = parameters.get('type')?.toLowerCase() as RecordType | undefined;
let recordId: string | null = parameters.get('id');
...
}
I would love to have something like this:
RouterModule.forRoot({ path: 'record/:type',
if: { param: 'type', value: 'species' },
component: NestedRecordComponent, ... },
{ path: 'record/:type', component: RecordComponent, ... }, ...)
Does anything like this exist? Or is there a way to pass on parent url segments to the child route?