我一直在使用Angular 2进行POC,我发现了一个问题:我无法获得子组件路由参数。
如您所见(代码如下),我有一个父组件名称ItemDetailComponent,它根据项目/ {id}路径参数(必需参数)显示有关项目的详细信息。
在这个组件中,我有一个名为RecommendationComponent的子项,它负责显示有关给定项目的所有建议(同样,基于{id}路径参数)。
我无法解决的问题(ItemRecommendationResolver illustred)项目/ {id}建议deps,因为ActivatedRoute.snapshot.params dosn没有注册{id}。
鉴于以下内容:
@Component({
selector: 'item-detail',
providers: [],
directives: [ProductDetailCardcomponent, RecommendationComponent],
styles: [],
templateUrl: './item-detailtemplate.html'
})
和recommendation.component
@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
}
}
]
}
];
和recommendation.component
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
];
是否有人可以帮助我,请求?
答案 0 :(得分:0)
您在ItemRecommendationResolver中获得的route
是路径recommendations
,它没有id参数。
如果您想获得id
,您应该获得此路线的父母并检查参数。喜欢
this.router.routerState.parent(this.route).params.subscribe(params => {
let id = params["id"];
});
同样见article