Reputation: 91
I want to have the following routes in my application:
export const routes: Routes = [
{
path: ':universityId',
component: UniversityComponent,
children: [
{ path: 'info', component: UniversityInfoComponent },
{ path: 'courses/:status', component: CoursesByStatusComponent }
]
}
]
Being on /1/info
or /1/courses/open
url, how do I change :universityId
only from UniversityComponent
?
Simple router.navigate(['../', 2], {relativeTo: currentRoute })
won't do because it redirects to /2
, losing all other information. Using '../2/courses/open
is also not an option - I can be on any child route at that moment.
Best I could come up with is:
const urlTree = this.router.parseUrl(this.router.url);
urlTree.root.children['primary'].segments[0].path = '2';
this.router.navigateByUrl(urlTree);
but it's kind of ugly
Upvotes: 9
Views: 1734
Reputation: 11
This is very simple. You can simply try to use this.router.navigate(["../2", "courses", "open"], {relativeTo: this.route});
(or)
this.router.navigate(["../2", "courses/open"], {relativeTo: this.route});
This will redirect you to ../2/courses/open.
Upvotes: 1
Reputation: 8904
Here is some code to go along with my comment above about using Tuples: So replicate this pattern twice... This shows how to integrate these classes into your project. So:
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Parent} from '../shared/model/parent';
import {Children} from '../shared/model/children';
import {ParentService} from '../providers/parent.service';
@Injectable()
export class parentChildResolver implements Resolve<[Parent,(Children[])>
constructor(private parentService : ParentService) {}
resolve( route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) : Observable<[Parent,(Children[])>
{
return this.parentService.findParentById(route.params['id'])
.switchMap(parent =>
this.parentService.findChildrenForParent(parent.id),
(parent, children) => [parent, children]
);
}
}
import {Component, OnInit} from '@angular/core';
import {Parent} from '../shared/model/parent';
import {Children} from '../shared/model/children';
import {Observable} from 'rxjs';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'parent-child',
templateUrl: './parent-child.component.html'
})
export class ParentChildComponent implements OnInit{
$parent: Observable<Parent>;
$children: Observable<Children[]>;
constructor(private route:ActivatedRoute) {}
ngOnInit() {
this.parent$ = this.route.data.map(data => data['key'][0]); //from router.config.ts
this.children$ = this.route.data.map(data => data['key'][1]);
}
}
Upvotes: 0