【发布时间】:2016-08-03 17:05:31
【问题描述】:
我一直在使用 Angular 2 开发 POC,但我发现了一个问题:我无法获取子组件路由参数。
如您所见(代码如下),我有一个父组件名称 ItemDetailComponent,它根据 item/{id} 路径参数(必需参数)显示有关项目的详细信息。
在这个组件中,我有一个名为 RecommendationComponent 的子组件,它负责显示关于给定项目的所有建议(同样,基于 {id} 路径参数)。
由于 ActivatedRoute.snapshot.params 没有注册 {id},因此我无法解决(ItemRecommendationResolver 如下所示)项目/{id}建议依赖的问题。
给定以下组件:
@Component({
selector: 'item-detail',
providers: [],
directives: [ProductDetailCardcomponent, RecommendationComponent],
styles: [],
templateUrl: './item-detailtemplate.html'
})
和推荐组件
@Component({
selector: 'recommendations',
styles: [],
providers: [],
templateUrl: './recommendation.template.html',
directives: []
})
export class ItemDetailComponent implements OnInit, OnDestroy {
private item: any;
private sub: any;
constructor(private itemService: ItemService, private route: ActivatedRoute) { }
ngOnInit() {
this.getItems();
}
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
}
public getItems() {
let id= this.route.snapshot.params['id'];
this.route.params.subscribe(params => {
this.itemService
.getItem(id)
.subscribe(item => this.item = item);
});
}
}
还有 item.routes.ts
export const itemRoutes Routes: RouterConfig = [
{
path: 'items',
component: ItemComponent
},
{
path: 'items/:id',
component: ItemDetailComponent,
children: [
{
path: 'recommendations',
component: RecommendationComponent,
resolve: {
recommendations: ItemRecommendationResolver
}
}
]
}
];
和推荐组件
export class RecommendationComponent implements OnInit, OnDestroy {
private recommendations: any;
private errorMessage: any;
private sub: any;
constructor(private route: ActivatedRoute, private router: Router) { }
getRecommendations() {
this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
let id = params["id"];
});
this.route
.data
.subscribe((data: any) => {
this.recommendations = data.recommendations;
});
}
ngOnInit() {
this.getRecommendations();
}
}
和 item.resolver
@Injectable()
export class ItemRecommendationResolver implements Resolve<any>, OnDestroy {
constructor(private itemService: ItemService, private route: ActivatedRoute, private router: Router) { }
private sub: any;
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let id = this.route.snapshot.params['id']; // can't get the item/{id} value. So I won't be able to retrieve the item recommendations.
return this.itemService.getItemsRecommendations(id);
}
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
}
}
export const ITEM_RESOLVER = [
ItemService,
ItemRecommendationResolver
];
请问有人可以帮我吗?
【问题讨论】:
标签: angular angular2-routing angular-routing