如何按JSON响应的category字段分类展示对象到Angular 10轮播组件
Angular 10 按课程分类渲染轮播实现方案
1. 处理后端返回数据(组件TS文件)
首先定义课程数据结构,请求接口后将课程按category字段分组:
// 定义课程数据类型 interface Course { id: number; name: string; category: string; description: string; preview_image: string; created_at: string; } // 组件内定义分组后存储的变量 groupedCourses: Record<string, Course[]> = {}; // 假设getCourses是你请求PHP接口的方法,拿到响应后处理 this.http.post('你的PHP接口地址', params).subscribe((res: any) => { // 按category字段分组 this.groupedCourses = res.course.reduce((groups, course: Course) => { const category = course.category; if (!groups[category]) { groups[category] = []; } groups[category].push(course); return groups; }, {} as Record<string, Course[]>); // 如果只需要保留指定分类,可加以下过滤逻辑 const allowCategories = ['Basic Training', 'Policy Training']; this.groupedCourses = Object.fromEntries( Object.entries(this.groupedCourses).filter(([cate]) => allowCategories.includes(cate)) ); });
2. 模板渲染轮播(component.html文件)
使用Angular的keyvalue管道遍历分组对象,每个分类对应一个轮播组件,以下示例以常用的ngx-owl-carousel-o轮播组件为例,你可以替换为项目中使用的任意轮播组件:
<!-- 遍历所有分类 --> <ng-container *ngFor="let cateGroup of groupedCourses | keyvalue"> <!-- 分类标题 --> <h2>{{ cateGroup.key }}</h2> <!-- 轮播组件 --> <owl-carousel-o [options]="carouselConfig"> <!-- 遍历当前分类下的所有课程 --> <ng-template carouselSlide *ngFor="let course of cateGroup.value"> <div class="course-item"> <img [src]="course.preview_image" [alt]="course.name"> <h3>{{ course.name }}</h3> <p>{{ course.description }}</p> </div> </ng-template> </owl-carousel-o> </ng-container>
如果你的项目没有使用第三方轮播,直接替换上面的轮播组件代码为你自己的轮播结构即可,核心逻辑是先按分类分组,再分别遍历每个分类下的课程数据。
内容的提问来源于stack exchange,提问作者user14724102
相关产品推荐
相关产品推荐

