我想在我的应用程序中使用以下路径:
export const routes: Routes = [
{
path: ':universityId',
component: UniversityComponent,
children: [
{ path: 'info', component: UniversityInfoComponent },
{ path: 'courses/:status', component: CoursesByStatusComponent }
]
}
]
在/1/info
或/1/courses/open
网址上,如何仅从:universityId
更改UniversityComponent
?
简单router.navigate(['../', 2], {relativeTo: currentRoute })
不会因为重定向到/2
而失去所有其他信息。使用'../2/courses/open
也不是一种选择 - 那时我可以在任何子路线上。
我能想出的最好的是:
const urlTree = this.router.parseUrl(this.router.url);
urlTree.root.children['primary'].segments[0].path = '2';
this.router.navigateByUrl(urlTree);
但它有点丑陋
答案 0 :(得分:0)
以下是一些与我上面关于使用元组的评论相关的代码:所以复制这个模式两次......这个shows如何将这些类集成到你的项目中。 所以:
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]);
}
}
答案 1 :(得分:0)
这很简单。 您可以简单地尝试使用 this.router.navigate([“ ../ 2”,“路线”,“开放”],{relativeTo:this.route});
(或)
this.router.navigate([“ ../ 2”,“课程/开放”],{relativeTo:this.route});
这会将您重定向到../ 2 / courses / open。