Angular+Supabase项目按单次测试筛选展示答题详情问题
问题根因
现有代码两个核心逻辑错误导致无法按单次测试展示数据:
- 详情页跳转时未传递当前点击的单次测试唯一标识,错误传入用户邮箱作为路由参数,无法定位具体是哪次测试
- 详情页拉取答题详情后仅按用户ID过滤,未关联单次测试维度做筛选,因此会展示该用户所有历史答题数据
分步修改方案
1. 修改profile页逻辑,正确传递单次测试ID
- 修正TS中的跳转方法,路由携带当前点击的测试记录唯一标识(即result表的主键,通常为
id字段,若表结构自定义则替换为实际关联字段)
// 替换原有错误的goToDetail方法 goToDetail(testId: string | number){ this.router.navigate(['account/user', this.session2?.user?.email], { queryParams: { testId: testId } }); }
- 修正profile页HTML中详情按钮的传参,传入当前循环项的测试ID,同时补全缺失的
td标签修复表格结构问题
<!-- 替换原有按钮所在行的代码 --> <td> <button nz-button nzType="primary" (click)="goToDetail(res.id)">Dettagli</button> </td>
注意:若你的result表主键字段名不是id,替换为实际的单次测试唯一标识字段即可
2. 修改profile-detail页逻辑,按传入的测试ID过滤数据
- 首先在组件constructor中注入
ActivatedRoute用于读取路由参数,新增组件变量存储当前测试ID
currentTestId: string | number | null = null; // constructor示例,补充ActivatedRoute注入 constructor( // 保留原有依赖注入项 private route: ActivatedRoute ) { }
- 修正ngOnInit中的数据查询逻辑,优先在数据库查询层面过滤数据(性能最优,无需拉取全量答题记录),如果暂时不修改Supabase服务层方法,可临时使用前端过滤
ngOnInit(): void { // 读取路由传递的单次测试ID this.route.queryParams.subscribe(params => { this.currentTestId = params['testId']; if (!this.currentTestId) return; // 推荐方案:直接调用Supabase查询时加过滤条件,仅拉取当前测试+当前用户的答题详情 // 注意:需要在SupabaseQuizService中新增getDetailsByTestId方法,查询条件匹配id_profile为当前用户id、关联测试id为传入的testId即可 this.supabase.getDetailsByTestId(this.currentTestId, this.userProfile?.id).subscribe((res: Details[]) => { this.det = res; }) // 临时前端过滤方案(不推荐长期使用,数据量大时会有性能损耗) // this.supabase.getDetails().subscribe((res: Details[]) => { // this.det = res.filter(item => item.id_profile === this.userProfile?.id && item.result_id === this.currentTestId) // }) }) // 保留原有用户信息、分类查询逻辑,删除原有的全量拉取详情无过滤的代码 this.supabaseUser.profile.then(profile => { if(profile.data){ this.userProfile = profile.data } }); this.supabase.getCategories().subscribe(res => { this.quizCategories = res; }) }
注意:确保你的答题详情表(details)中存储了关联测试概要表(result)的外键字段(通常命名为result_id),且同一次测试生成的所有详情记录该字段值与对应result记录的主键一致,否则无法完成关联筛选。如果之前存答题数据时未记录该关联字段,需要先修改答题提交时的存储逻辑,给同一次测试的所有答题详情绑定同一个测试概要ID
- 若使用前端过滤方案,可在详情页HTML的循环判断中补充测试ID匹配条件;如果已经在TS层完成数据过滤,可删除多余的判断逻辑直接渲染:
<!-- TS层已过滤的简化写法 --> <nz-table #basicTable> <thead> <tr> <th>Categoria</th> <th>Question</th> <th>Answer</th> <th>Date</th> </tr> </thead> <tbody> <tr *ngFor="let d of det"> <td>{{d.category_id}}</td> <td>{{d.question}}</td> <td>{{d.json_answer}}</td> <td>{{d.date}}</td> </tr> </tbody> </nz-table>
内容的提问来源于stack exchange,提问作者Lorenzo Dicara
相关产品推荐
相关产品推荐

