
在angular开发中,我们经常需要根据当前登录用户的身份来筛选和展示数据。一个常见的场景是,用户只能看到他们自己完成的测验结果。然而,在模板中直接进行复杂的过滤逻辑,特别是将*ngif嵌套在*ngfor内部以筛选数据,往往会导致结构性问题、性能下降,甚至语法错误。本文将深入探讨这种做法的问题,并提供一种更优雅、高效且符合angular最佳实践的解决方案。
原始的实现尝试在nz-table的<tbody>内部,对每一个<tr>元素使用*ngFor遍历result数组,然后在<tr>内部使用*ngIf来判断当前res.id_profile是否与userProfile?.id匹配。这种做法存在以下几个主要问题:
解决上述问题的核心原则是:将数据过滤的逻辑从模板层移至组件的TypeScript层。 这意味着在将数据绑定到视图之前,就完成所有必要的筛选和转换。
在组件的ngOnInit生命周期钩子中,当获取到用户的测验结果res和用户配置文件userProfile后,立即对res数组进行过滤。
import { Component, OnInit } from '@angular/core';
import { SupabaseService } from 'src/app/supabase.service'; // 假设你的Supabase服务
import { SupabaseQuizService } from 'src/app/supabase-quiz.service'; // 假设你的Supabase Quiz服务
import { Result } from 'src/app/models/result.model'; // 假设你的Result模型
import { Profile } from 'src/app/models/profile.model'; // 假设你的Profile模型
@Component({
selector: 'app-quiz-results',
templateUrl: './quiz-results.component.html',
styleUrls: ['./quiz-results.component.css']
})
export class QuizResultsComponent implements OnInit {
session2: any; // Supabase session
userProfile: Profile | null = null;
filteredResults: Result[] = []; // 用于存储过滤后的结果
constructor(
private supabase: SupabaseService,
private supabaseQuiz: SupabaseQuizService
) {}
ngOnInit(): void {
this.supabase.authChanges((_, session) => this.session2 = session);
this.getProfileAndResults();
}
async getProfileAndResults(): Promise<void> {
// 获取用户配置文件
const { data: profileData, error: profileError } = await this.supabase.profile;
if (profileError) {
console.error('Error fetching profile:', profileError.message);
// 处理错误,例如导航到错误页面
return;
}
if (profileData) {
this.userProfile = profileData;
// 只有在获取到用户ID后才去获取并过滤测验结果
this.loadQuizResults();
} else {
console.warn('No user profile found.');
// 提示用户创建档案或处理未登录情况
}
}
loadQuizResults(): void {
if (!this.userProfile?.id) {
console.warn('User profile ID is not available for filtering results.');
return;
}
this.supabaseQuiz.getResult().subscribe({
next: (allResults: Result[]) => {
// 使用Array.prototype.filter()方法在TypeScript中进行数据过滤
this.filteredResults = allResults.filter(
(res: Result) => res.id_profile === this.userProfile?.id
);
},
error: (err) => {
console.error('Error fetching quiz results:', err);
// 处理错误
}
});
}
goToDetail(parameterValue: any): void {
// 导航到详情页的逻辑
console.log('Go to detail for:', parameterValue);
}
}代码说明:
经过TypeScript层的过滤后,HTML模板变得非常简洁和语义化。它只需要遍历已经过滤好的filteredResults数组,并直接显示数据即可,无需任何额外的*ngIf条件判断。
<nz-table #headerTable [nzData]="filteredResults" [nzPageSize]="50" [nzScroll]="{ y: '240px' }">
<thead>
<tr>
<th>Category</th>
<th>Date</th>
<th>Correct answers</th>
<th>Final score</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- 直接遍历过滤后的数据,无需内部条件判断 -->
<tr *ngFor="let res of filteredResults">
<td>{{ res.categoryTitle }}</td>
<td>{{ res.date }}</td>
<td>{{ res.rightAnswer }}</td>
<td>{{ res.finalScore }}</td>
<td>
<button nz-button nzType="primary" success (click)="goToDetail(res.id)">Dettagli</button>
</td>
</tr>
</tbody>
</nz-table>
<!-- 当没有结果时显示提示 -->
<ng-container *ngIf="filteredResults.length === 0">
<p style="text-align: center; padding: 20px;">No quiz results found for this user.</p>
</ng-container>代码说明:
通过将数据过滤逻辑从Angular模板转移到TypeScript组件中,我们不仅解决了因不当使用*ngIf和*ngFor导致的结构性问题和语法错误,还提升了代码的可读性、可维护性和性能。这种“数据先行,视图随后”的开发模式是Angular乃至所有前端框架中处理数据展示的黄金法则。遵循这些最佳实践,将帮助开发者构建更健壮、更高效的Angular应用。
以上就是Angular中用户特定数据展示与模板过滤优化指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号