我一直在用Angular 2處理POC,並且發現了一個問題:我無法獲取子組件路由參數。您可以看到(代碼如下所示),我有一個父組件名稱ItemDetailComponent,它顯示基於項目/ {id}路徑參數(必需參數)的項目的詳細信息。如何解決在Angular 2中的兒童參數
在這個組件中,我有一個名爲RecommendationComponent的子組件,它負責顯示關於給定項目的所有建議(同樣基於{id}路徑參數)。
我無法解決的問題(ItemRecommendationResolver illustred bellow)項目/ {id}建議縮減,因爲ActivatedRoute.snapshot.params沒有註冊{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
];
是否有任何人可以幫助我,普萊舍?
也試過這種方法,但顯然routerState.parent()的定義。 得到此錯誤消息: 錯誤:未被捕獲(承諾):TypeError:無法讀取屬性'參數'null 您是否有任何其他想法可以解決該問題? –
你可以手動驗證routeState(ActivatedRoute的樹)是否有你需要的信息。由於參考不匹配/不存在,父可能會返回null。如果ref不匹配,我們可以編寫一些代碼從樹中獲取父項。 –
剛剛確認。父母它的空。 我該如何解決它? –