设计思路
- 输入参数:管道接受商品价格作为输入,同时可以接受用户所在地、会员等级等作为可选参数。这样可以灵活地根据不同的条件进行价格格式化。
- 业务逻辑封装:在管道内部,根据不同的用户所在地(可能对应不同的货币符号、千位分隔符等规则)和会员等级(可能对应不同的折扣显示方式等),编写相应的格式化逻辑。例如,根据用户所在地确定货币符号和小数位数,根据会员等级确定是否显示折扣价格等。
- 缓存机制:为了提高性能,对于相同输入参数的格式化结果可以进行缓存。这样在相同条件下再次调用管道时,可以直接返回缓存结果,减少重复计算。
实现步骤
- 创建自定义管道:使用Angular CLI命令
ng generate pipe priceFormat
生成管道文件,例如 price - format.pipe.ts
。
- 编写管道逻辑:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'priceFormat'
})
export class PriceFormatPipe implements PipeTransform {
private cache: { [key: string]: string } = {};
transform(price: number, location: string, memberLevel: string): string {
const key = `${price}-${location}-${memberLevel}`;
if (this.cache[key]) {
return this.cache[key];
}
let formattedPrice = '';
// 根据location确定货币符号和千位分隔符等规则
if (location === 'China') {
formattedPrice = '¥ ' + price.toLocaleString('zh - CN', { minimumFractionDigits: 2 });
} else if (location === 'USA') {
formattedPrice = '$ ' + price.toLocaleString('en - US', { minimumFractionDigits: 2 });
}
// 根据memberLevel确定是否显示折扣价格等
if (memberLevel === 'VIP') {
const discountPrice = price * 0.8;
formattedPrice += ` (VIP Discount: $${discountPrice.toLocaleString('en - US', { minimumFractionDigits: 2 })})`;
}
this.cache[key] = formattedPrice;
return formattedPrice;
}
}
- 在模板中使用:
<div>
<p>Formatted Price: {{ productPrice | priceFormat: userLocation: userMemberLevel }}</p>
</div>
确保可维护性和扩展性
- 模块化代码:将不同的格式化逻辑封装成独立的函数,在
transform
方法中调用。这样如果需要修改某种条件下的格式化逻辑,只需要修改对应的函数,而不会影响其他部分。
- 注释清晰:对关键的逻辑部分添加注释,特别是处理不同条件的部分,方便其他开发者理解和维护代码。
- 扩展性:
- 参数扩展:如果未来需要增加新的影响价格格式化的因素,比如促销活动等,可以在管道的
transform
方法中增加新的参数来处理。
- 逻辑扩展:可以在管道内部新增函数来处理新的格式化逻辑,并且在
transform
方法中调用,而不会破坏原有的代码结构。同时,缓存机制也能适应新参数的变化,因为新参数会成为缓存键的一部分。