我有一个 @Routeconfig
(父母)的组件 .
import {Component} from "angular2/core";
import {RouteConfig,ROUTER_DIRECTIVES, RouterOutlet} from 'angular2/router';
import {Theme} from "../theme/theme";
import {Router,RouteParams} from "angular2/router";
import {OrganisationService} from "./organisation.service";
import {Organisation} from "./organisation";
import {OrganisationComponent} from "./organisation.component";
import {EmptyComponent} from "../../empty.component";
import {ThemeListComponent} from "../theme/theme-list.component";
@Component({
template: `
<div class="container">
<ul>
<li *ngFor="#organisation of organisations">
<a [routerLink]="['./ThemeList',{ organisationId: organisation.organisationId }]" >{{organisation.organisationName}}</a>
</li>
</ul>
</div>
<router-outlet></router-outlet>
`,
directives:[RouterOutlet],
providers:[OrganisationService]
})
@RouteConfig([
{path: '/', name:'Empty', component:EmptyComponent,useAsDefault: true},
{path: '/:organisationId/Themes/...', name:'ThemeList', component:ThemeListComponent}
])
export class OrganisationListComponent {
public organisations:Organisation[];
constructor(private organisationService:OrganisationService) {
this.organisationService.getOrganisations().subscribe((organisations:Organisation[])=> {
this.organisations = organisations;
});
}
}
我想将组织中的id发送给我的 ThemeListComponent
(孩子) . 这有效,但当我尝试使用我的子组件获取routeParams时,它会产生错误 .
EXCEPTION:在实例化路由器期间出错! (RouterLink - >路由器) . 原始例外:路由配置应该只包含一个“组件”,“加载器”或“redirectTo”属性 .
这是ThemeListComponent以及我如何尝试接收routerParams:
import {Component} from "angular2/core";
import {RouteConfig,ROUTER_DIRECTIVES, RouterOutlet} from 'angular2/router';
import {Theme} from "../theme/theme";
import {Router,RouteParams} from "angular2/router";
import {ThemeComponent} from "../theme/theme.component";
import {ThemeService} from "./theme.service";
import {EmptyComponent} from "../../empty.component";
@Component({
template: `
<div class="container">
<ul>
<li *ngFor="#theme of themes">
<a [routerLink]="['./Theme',{ themeId: theme.themeId }]">{{theme.name}}</a>
</li>
</ul>
</div>
<router-outlet></router-outlet>
`,
directives:[RouterOutlet,RouteParams],
providers:[ThemeService]
})
@RouteConfig([
{path: '/', name:'Empty', component:EmptyComponent,useAsDefault: true},
{path: '/:themeId', name:'Theme', component:ThemeComponent}
])
export class ThemeListComponent {
public themes:Theme[];
constructor(private themeService:ThemeService,private routeParams:RouteParams) {
let id = +this.routeParams.get('id');
this.themeService.getThemes(id).subscribe((themes:Theme[])=>{
this.themes = themes;
});
}
}
每当我在孩子的构造函数中实现routerParams时,我都会收到错误 .
2 回答
我有类似的问题 . 我通过简单地将RouteParams和Router与RouteConfig,ROUTER_DIRECTIVES,RouterOutlet放在同一行来解决它 .
这可能会给你一个错误 . 所以我改变了
至
不知何故,我不明白为什么这不适用于两个单独的导入,但这应该解决问题 .
目前没有简单的方法 . 另见https://github.com/angular/angular/issues/6985
Angular 2: getting RouteParams from parent component提供了一些解决方法 .