【问题标题】:How to display a list of sub-categories using JSON data如何使用 JSON 数据显示子类别列表
【发布时间】:2019-10-22 19:20:48
【问题描述】:

我有一个 JSON 数组,其中包含一个类别数组。当我在应用程序中导航到“/beds”时,我希望它显示子类别列表,在本例中为“床架”。我有一个 SubCategoryComponent 用于每个子类别,为每个子类别设置单独的组件似乎没有意义,因为我将加载类似的页面。

如何让我的SubcategoryComponent 知道它应该加载正确的数据?当导航到“/beds”时,它应该加载“Bed Frames”子类别,而对于“/mattresses”,它应该加载相关的子类别。

我应该如何在模板中迭代它?目前它看起来像是一个嵌套循环,但肯定有更好的方法。

从我的服务函数返回的 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 },
    ]),

【问题讨论】:

  • 你能做一个stackblitz的例子吗

标签: angular


【解决方案1】:

我通过以下方式解决了这个问题:

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}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多