我有一个JSON数组,其中包含一个categorys数组。当我在应用程序中导航至“ / beds”时,我希望它显示子类别列表,在本例中为“ Bed Frames”。我有一个SubCategoryComponent
用于每个子类别,因为要加载相似的页面,每个子类别都具有单独的组件似乎没有意义。
如何让我的SubcategoryComponent
知道它应该加载正确的数据?导航到“ /床”时,应加载“床架”子类别,对于“ /床垫”,应加载相关的子类别。
如何在模板中对此进行迭代?目前,这似乎是一个嵌套循环,但是肯定有更好的方法。
从我的服务函数返回的JSON:
[
{
"name": "Beds",
"path": "/beds",
"categories" : [
"Bed Frames"
]
}
]
服务功能:
getTopLevelCategories(): Observable<ITopLevelCategory[]> {
return this.http.get<ITopLevelCategory[]>(this.topLevelCategoryUrl)
.pipe(
tap(data => console.log('All: ' + JSON.stringify(data))),
catchError(this.handleError)
);
}
路由器:
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'beds', component: SubcategoryComponent },
{ path: 'mattresses', component: SubcategoryComponent },
]),
答案 0 :(得分:0)
我通过以下操作解决了这个问题:
1:将data
数组添加到路由:
{ path: 'beds', component: SubcategoryComponent, data: {category: "/beds"} },
2:返回服务中的相关顶级类别
getCategory(category: string): Observable<ITopLevelCategory | undefined> {
return this.getTopLevelCategories()
.pipe(
map((toplevelcategories: ITopLevelCategory[]) => toplevelcategories.find(toplevelcategories => toplevelcategories.path === category))
);
}
3:获取组件中的类别
getCategory(category: string) {
this.topLevelCategoryService.getCategory(category).subscribe({
next: toplevelcategory => this.toplevelcategory = toplevelcategory,
error: err => this.errorMessage = err
});
}
4:输出模板中的子类别
{{toplevelcategory.categories}}