
本文旨在解决Primeng DataView在使用懒加载和分页时可能出现的重复API请求问题。通过在客户端实现页面数据的缓存机制,结合搜索参数的智能判断,优化了数据加载逻辑,确保仅在必要时才向后端发起请求,从而显著提升了数据视图的性能和用户体验,避免了不必要的网络开销和数据重复获取。
引言
Primeng的DataView组件提供了强大的数据展示能力,支持分页、排序和过滤等功能。当处理大量数据时,结合懒加载(Lazy Loading)模式可以显著提高前端应用的响应速度和用户体验,因为它只在需要时才从后端获取数据。然而,在实现懒加载和分页功能时,尤其是在用户频繁切换页面或应用搜索/过滤条件时,如果不进行适当的优化,可能会导致重复的API请求,从而增加服务器负担和降低客户端性能。
本文将详细探讨如何通过在客户端实现智能的页面数据缓存机制,来优化Primeng DataView的懒加载和分页行为,确保数据仅在首次加载或搜索条件发生变化时从API获取,而在用户访问已加载过的页面时直接从缓存中获取。
面临的挑战
在Primeng DataView中,当[lazy]=”true”时,onLazyLoad事件会在组件初始化、分页、排序或过滤条件改变时触发。如果同时使用onPage事件,或者在onLazyLoad内部不加区分地进行API调用,可能会遇到以下问题:
- 重复API请求: 用户在不同页面之间切换时,即使数据已经加载过,也可能再次触发API请求。
- 数据不一致: 如果API请求频率过高,或者处理逻辑不当,可能导致DataView显示的数据与实际期望的数据不符。
- 性能下降: 频繁的网络请求会增加延迟,消耗用户带宽,尤其是在移动网络环境下,用户体验会大打折扣。
初始的尝试可能包括在onPageChange和loadProducts中都进行API调用,但这会导致API请求的重复发送,并且由于异步操作,数据更新可能混乱。
解决方案:客户端页面缓存与智能请求
为了解决上述问题,我们引入一个客户端缓存机制,利用一个JavaScript对象来存储已加载的每一页数据。当用户请求某一页数据时,首先检查缓存中是否存在该页数据;如果存在且搜索条件未改变,则直接使用缓存数据;否则,才向API发起请求。
核心思路
- 缓存结构: 使用一个对象(例如 pagesItems),以页码作为键,存储对应页的产品列表作为值。
- 搜索参数跟踪: 除了缓存产品数据,还需要存储当前的搜索参数(如 name, category, brands, priceRange, size),以便在用户切换页面时判断搜索条件是否发生变化。
- 条件性API请求: 在onLazyLoad事件处理函数中,根据当前请求的页码和存储的搜索参数,决定是从缓存中读取数据还是发起新的API请求。
- 强制刷新: 提供一个机制,例如搜索按钮点击,来强制清除缓存并重新发起API请求。
实现步骤
1. 定义数据接口
为了清晰地表示分页产品和搜索参数,我们定义以下接口:
// src/app/interface/product/pagable-products.ts export interface PageableProducts { products: Product[]; total_pages: number; total_products: number; } // src/app/interface/product/product.ts export interface Product { id?: string; brand: string; name: string; price: number; category: string; subcategory: string; stock: number; description: string; image_url: string; } // src/app/interface/search/search.ts export interface Search { size: number; page: number; category?: string; subcategory?: string; brands?: string[]; priceRange?: number[]; name?: string; }
2. 产品服务 (ProductService)
产品服务负责向后端API发起请求,根据搜索参数获取分页产品数据。
// src/app/service/product.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http"; import { catchError, Observable, of, tap } from "rxjs"; import { PageableProducts } from "../interface/product/pagable-products"; import { Search } from "../interface/search/search"; @Injectable({ providedIn: 'root' }) export class ProductService { private productUrl: string = 'http://localhost:8080/product/api'; httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; constructor(private http: HttpClient) { } searchProducts(searchQuery: Search): Observable<PageableProducts> { let queryParams = new HttpParams(); // 构建查询参数 if (searchQuery.name) queryParams = queryParams.append("name", searchQuery.name); if (searchQuery.category) queryParams = queryParams.append("category", searchQuery.category); if (searchQuery.subcategory) queryParams = queryParams.append("subcategory", searchQuery.subcategory); if (searchQuery.brands && searchQuery.brands.length > 0) queryParams = queryParams.append("brands", searchQuery.brands.join(',')); // 假设后端接受逗号分隔 if (searchQuery.priceRange && searchQuery.priceRange.length === 2) { queryParams = queryParams.append("pMin", searchQuery.priceRange[0]); queryParams = queryParams.append("pMax", searchQuery.priceRange[1]); } if (searchQuery.page !== null && searchQuery.page >= 0) queryParams = queryParams.append("page", searchQuery.page); if (searchQuery.size !== null && searchQuery.size > 0) queryParams = queryParams.append("size", searchQuery.size); console.log(`Sending API request with params: ${queryParams.toString()}`); return this.http.get<PageableProducts>(`${this.productUrl}/public/search`, { params: queryParams }).pipe( tap(_ => console.log(`Fetched products for page ${searchQuery.page}`)), catchError(this.handleError<PageableProducts>('searchProducts', { products: [], total_pages: 0, total_products: 0 })) ); } private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(`${operation} failed: ${error.message}`); return of(result as T); }; } }
3. 搜索组件 (SearchComponent)
这是实现缓存逻辑的核心部分。
// src/app/search/search.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { Product, PageableProducts } from '../interface/product/product'; // 假设Product和PageableProducts在同一个文件 import { Search } from '../interface/search/search'; import { ProductService } from '../service/product.service'; import { CategoryService } from '../service/category.service'; // 假设存在 import { BrandService } from '../service/brand.service'; // 假设存在 import { CategoryDto } from '../interface/category/category-dto'; // 假设存在 import { BrandDto } from '../interface/brand/brand-dto'; // 假设存在 import { StorageService } from '../service/storage.service'; // 假设存在,用于购物车 @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { virtualProducts: Product[] = []; // Primeng DataView实际显示的数据 selectedSize = 40; // 每页产品数量 totalRecords = 0; // 总产品数量 selectedPage = 0; // 当前页码 (0-indexed) first = 0; // Primeng DataView的first属性,表示当前页第一条记录的索引 // 搜索参数 name?: string; category: string = ''; subcategory?: string; selectedBrands: string[] = []; priceRange: number[] = [0, 4000]; selectedPriceRange: number[] = [20, 1000]; // 过滤选项 subcategories: string[] = []; brands: string[] = []; sizeOptions: number[] = [5, 20, 40, 60, 80, 100, 200, 500]; loading: boolean = false; // DataView的加载状态 pagesItems: { [key: string]: any } = {}; // 客户端缓存,键为页码或'searchParams'/'size'等 constructor( private categoryService: CategoryService, private brandService: BrandService, private productService: ProductService, private route: ActivatedRoute, private titleService: Title, private storageService: StorageService // 用于购物车功能 ) { } ngOnInit(): void { this.route.params.subscribe(params => { this.category = params['category']; this.updateFilterValues(); // 获取分类和品牌选项 if (this.category) { this.titleService.setTitle(this.category); } // 页面初始化时,根据当前路由参数构建初始搜索条件 const initialSearchParams: Search = { size: this.selectedSize, page: this.selectedPage, category: this.category, subcategory: this.subcategory, brands: this.selectedBrands, priceRange: this.selectedPriceRange, name: this.name }; // 发起初始搜索请求 this.search(initialSearchParams); // 延迟更新virtualProducts,确保API响应已到达并缓存 setTimeout(() => { if (this.pagesItems[this.selectedPage]) { this.virtualProducts = [...this.pagesItems[this.selectedPage]]; } }, 500); // 适当调整延迟时间 }); } /** * 向API发起产品搜索请求,并将结果缓存。 * @param searchParams 当前的搜索参数。 */ search(searchParams: Search): void { this.loading = true; this.productService.searchProducts(searchParams).subscribe({ next: (value: PageableProducts) => { // 缓存当前的搜索参数和分页大小 this.pagesItems['searchParams'] = { category: searchParams.category, subcategory: searchParams.subcategory, brands: searchParams.brands, priceRange: searchParams.priceRange, name: searchParams.name }; this.pagesItems['size'] = searchParams.size; this.pagesItems['page'] = searchParams.page; // 缓存当前请求的页码 // 缓存当前页的产品数据 this.pagesItems[searchParams.page] = [...value.products]; this.totalRecords = value.total_products; this.loading = false; console.log(`API fetched page ${searchParams.page}, total products: ${this.totalRecords}`); }, error: (err) => { console.error('Search API error:', err); this.loading = false; } }); } /** * Primeng DataView的onLazyLoad事件处理函数。 * 根据分页或搜索条件变化,决定从缓存加载或发起API请求。 * @param event LazyLoadEvent对象,包含first、rows等信息。 * @param isButtonClicked 标记是否由搜索按钮点击触发,用于强制刷新缓存。 */ loadProducts(event: any, isButtonClicked: boolean): void { this.loading = true; this.first = event.first; this.selectedSize = event.rows; this.selectedPage = Math.floor(this.first / this.selectedSize); // 计算当前页码 const currentSearchParams: Search = { size: this.selectedSize, page: this.selectedPage, category: this.category, subcategory: this.subcategory, brands: this.selectedBrands, priceRange: this.selectedPriceRange, name: this.name }; // 如果是搜索按钮点击,或者搜索条件发生变化,则清空缓存并重新开始 if (isButtonClicked || (this.pagesItems && !this.isSameSearchParams(currentSearchParams))) { this.pagesItems = {}; // 清空整个缓存 this.pagesItems['searchParams'] = { ...currentSearchParams }; // 更新为新的搜索参数 this.pagesItems['size'] = this.selectedSize; this.pagesItems['page'] = this.selectedPage; } // 检查缓存中是否存在当前页的数据 if (this.pagesItems[this.selectedPage] === undefined) { console.log(`Page ${this.selectedPage} not in cache. Fetching from API...`); // 如果缓存中没有,则发起API请求 this.search(currentSearchParams); // 延迟更新virtualProducts,等待API响应并缓存 setTimeout(() => { if (this.pagesItems[this.selectedPage]) { this.virtualProducts = [...this.pagesItems[this.selectedPage]]; } this.loading = false; event.forceUpdate = true; // 强制DataView更新 }, 500); // 适当调整延迟时间 } else { console.log(`Page ${this.selectedPage} found in cache. Loading from cache...`); // 如果缓存中有,则直接从缓存加载 this.virtualProducts = [...this.pagesItems[this.selectedPage]]; this.loading = false; event.forceUpdate = true; // 强制DataView更新 } } /** * 比较当前搜索参数与缓存中的搜索参数是否一致。 * 用于判断是否需要清空缓存并重新搜索。 * @param currentParams 当前的搜索参数。 * @returns 如果搜索参数一致则返回true,否则返回false。 */ isSameSearchParams(currentParams: Search): boolean { const cachedParams = this.pagesItems['searchParams']; if (!cachedParams) return false; // 缓存中没有搜索参数,视为不一致 // 比较各个搜索字段,注意数组和对象的深层比较 const areBrandsSame = JSON.stringify(currentParams.brands?.sort()) === JSON.stringify(cachedParams.brands?.sort()); const arePriceRangeSame = JSON.stringify(currentParams.priceRange) === JSON.stringify(cachedParams.priceRange); return currentParams.name === cachedParams.name && currentParams.category === cachedParams.category && currentParams.subcategory === cachedParams.subcategory && areBrandsSame && arePriceRangeSame && currentParams.size === this.pagesItems['size']; // 也要比较每页大小 } /** * 搜索按钮点击事件,重置分页并强制刷新缓存。 */ OnSearchButtonClick(): void { this.first = 0; // 重置到第一页 this.loadProducts({ first: this.first, rows: this.selectedSize, forceUpdate: true }, true); } // --- 其他辅助方法 --- private fetchCategories(category: string): void { this.categoryService.getSubcategoriesByCategoryName(category).subscribe((categories: CategoryDto[]) => { this.subcategories = categories.map((c: CategoryDto) => c.name); }); } private fetchBrands(category: string): void { this.brandService.getBrandsByCategoryName(category).subscribe((brands: BrandDto[]) => { this.brands = brands.map((b: BrandDto) => b.name); }); } updateFilterValues(): void { if (this.category) { this.fetchCategories(this.category); this.fetchBrands(this.category); } } addToCart(productId: string | undefined): void { if (productId) { this.storageService.addToCart(productId); console.log('Cart:', this.storageService.getCart()); } } }
4. HTML模板 (search.component.html)
DataView组件的配置需要绑定到组件的属性和事件上。
<!-- src/app/search/search.component.html --> <div class="flex-container"> <div class="flex-item"> <div class="p-inputgroup"> <input type="text" class="p-inputtext" placeholder="Search" [(ngModel)]="name"> <button pButton pRipple class="pi" (click)="OnSearchButtonClick()"><i class="pi pi-search"></i></button> </div> </div> <p-divider></p-divider> <div class="card flex"> <span>Price Range: {{selectedPriceRange[0]}} - {{selectedPriceRange[1]}}</span><br><br> <p-slider [(ngModel)]="selectedPriceRange" [range]="true" [min]="priceRange[0]" [max]="priceRange[1]" aria-label="label_number" (onSlideEnd)="OnSearchButtonClick()"></p-slider> </div> <p-divider></p-divider> <div class="flex-item"> <div> <p-dropdown [options]="subcategories" [(ngModel)]="subcategory" placeholder="Choose a Category" (onChange)="OnSearchButtonClick()"></p-dropdown> </div> <div> <p-multiSelect [options]="brands" [(ngModel)]="selectedBrands" placeholder="Choose Brands" (onChange)="OnSearchButtonClick()"></p-multiSelect> </div> </div> </div> <p-divider></p-divider> <p-dataView [value]="virtualProducts" [first]="first" [totalRecords]="totalRecords" [rows]="selectedSize" [rowsPerPageOptions]="sizeOptions" [paginator]="true" [pageLinks]="5" [lazy]="true" [loading]="loading" (onLazyLoad)="loadProducts($event,false)"> <ng-template let-product pTemplate="listItem"> <div class="col-12"> <div class="flex flex-column xl-flex-row xl-align-items-start p-4 gap-4"> <div class="flex flex-column sm-flex-row justify-content-between align-items-center xl-align-items-start flex-1 gap-4"> <div class="flex flex-column align-items-center sm-align-items-start gap-3"> <a [routerLink]="['/product', product.id]"> <div class="text-2xl font-bold text-900">{{ product.name }}</div> </a> <div class="flex align-items-center gap-3"> <span class="flex align-items-center gap-2"> <i class="pi pi-tag"></i> <span class="font-semibold">{{ product.subcategory }}
以上就是Primeng DataViewcss javascript java html js 前端 json go app 懒加载 后端 ai 路由 JavaScript html 接口 对象 事件 异步


