我在使用Angular2路线时遇到了麻烦。我有几个级别的嵌套。这是我的设置:我为未经身份验证的用户提供了最高级别的路由。登录后,它们位于/my
路径下。在该级别上,他们有一个仪表板,可以将它们带到/my/projects/
级别。 projects
下的路由需要ID。设置细节如下。
这是顶级AppComponent
:
@RouteConfig([
{path: '/home', name:'Home', component: HomeComponent, useAsDefault: true},
{path: '/login', name: 'Login', component: LoginComponent},
{path: '/signup', name: 'SignUp', component:SignUpComponent},
{path: '/my/...', name: 'MyApp', component: MyAppComponent}
])
export class AppComponent {
constructor(private router: Router) {
}
经过身份验证后,用户会转到MyAppComponent,其设置如下:
@RouteConfig([
{path:'/dashboard', name: 'MyDashboard', component: DashboardComponent, useAsDefault: true},
{path: '/projects/...', name: 'MyProjects', component: ProjectRootComponent},
])
export class MyAppComponent {
constructor(private router: Router) {
}
}
DashboardComponent:
export class DashboardComponent {
public projects: Array<Project>;
public loaded: boolean;
public loadError: boolean;
constructor(private _service: ProjectService, private router:Router) {
this.projects = [];
this.loaded = false;
}
ngOnInit() {
console.log('Dashboard component initialized');
this._service.getUserProjects()
.then(projects => {
this.loaded = true;
this.projects = projects;
},
error => {
this.loaded = true;
this.loadError = error;
});
}
selectProject(project: Project) {
// this.router.navigateByUrl('/my/projects/' + project.id); // Tried this approach as well with the same error
this.router.parent.navigate(['MyApp', 'MyProjects', {id: project.id}]);
}
在DashboardComponent上,我加载了一个项目列表。当我单击某个项目时,将调用selectProject(project)
方法,该方法应该导航到该项目页面。项目id
作为参数传入。 MyProjects路由需要一个id,并设置如下:
@RouteConfig ([
{path: '/:id', name: 'ProjectHome', component: ProjectHomeComponent, useAsDefault: true},
{path: '/:id/details', name: 'ProjectDetails', component: ProjectDetailsComponent },
])
export class ProjectRootComponent implements OnInit {
id: string;
constructor(private router: Router, private routeParams: RouteParams, private projectService: ProjectService) {
}
ngOnInit() {
this.id = this.routeParams.get('id');
console.log('Project Component Initialized with id: ' + this.id);
}
createProject() {
}
}
当仪表板上的selectProject(project)
被调用时,我收到错误:ORIGINAL EXCEPTION: Route generator for 'id' was not included in parameters passed.
我还尝试使用以下两种方法直接导航到项目详细信息:
this.router.parent.navigate(['MyApp', 'MyProjects', {id: project.id}, 'ProjectDetails']
和
this.router.parent.navigate(['MyApp', 'MyProjects', 'ProjectDetails', {id: project.id}]
两者都会产生与上述相同的错误。
注意:这与前面提到的this question类似,但我的路线已经按照该问题的答案中的建议设置。
答案 0 :(得分:7)
我认为您有路由查找问题,因为您正在从子路由导航。来自RouterLink
docs(linkParams
应该相同):
第一个路径名称应以/,。/或../为前缀。如果路由以/开头,则路由器将从应用程序的根目录查找路由。如果路由以./开头,则路由器将查找当前组件的子路由。如果路由以../开头,路由器将查看当前组件的父节点。
我相信这应该有效:
this.router.navigate(['/MyApp', 'MyProjects', 'ProjectDetails', {id: project.id}]
或从信息中心:
this.router.navigate(['./MyProjects', 'ProjectDetails', {id: project.id}]