MST

星途 面试题库

面试题:Angular货币转换管道在复杂场景下的优化与扩展

在一个大型Angular企业级应用中,不同用户可能有不同的货币偏好和显示格式需求。基于货币转换管道,如何设计一个通用的解决方案,使得在不大量重复代码的情况下,能够灵活满足各种货币显示需求,包括货币符号位置、小数位数、千位分隔符样式等,同时考虑性能优化,例如减少不必要的管道计算。请阐述设计思路,并给出关键代码示例。
16.8万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 创建可配置的货币转换管道
    • 定义一个货币转换管道,该管道接受多个配置参数,如货币符号位置、小数位数、千位分隔符样式等。这样可以根据不同用户需求灵活配置,避免重复代码。
    • 使用 @Pipe 装饰器来创建管道,并在 transform 方法中实现具体的转换逻辑。
  2. 缓存计算结果
    • 为了减少不必要的管道计算,可以在管道内部缓存计算结果。通过记录上一次的输入值和配置参数,当相同的输入再次出现时,直接返回缓存的结果,而不需要重新计算。
  3. 依赖注入
    • 如果货币转换需要依赖一些外部服务(如汇率获取服务),使用Angular的依赖注入机制来提供这些服务,使管道更加可测试和可维护。

关键代码示例

  1. 创建货币转换管道
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'currencyFormat',
  pure: false // 设置为不纯管道,以便在输入值或配置变化时重新计算
})
export class CurrencyFormatPipe implements PipeTransform {
  private cache: { [key: string]: string } = {};

  transform(
    value: number,
    currencySymbol: string = '$',
    symbolPosition: 'before' | 'after' = 'before',
    decimalDigits: number = 2,
    thousandSeparator: string = ','
  ): string {
    const cacheKey = `${value}-${currencySymbol}-${symbolPosition}-${decimalDigits}-${thousandSeparator}`;
    if (this.cache[cacheKey]) {
      return this.cache[cacheKey];
    }
    const numberPart = value.toFixed(decimalDigits).split('.');
    const integerPart = numberPart[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
    const decimalPart = numberPart[1];
    const formattedValue = symbolPosition === 'before'? `${currencySymbol}${integerPart}.${decimalPart}` : `${integerPart}.${decimalPart}${currencySymbol}`;
    this.cache[cacheKey] = formattedValue;
    return formattedValue;
  }
}
  1. 在模板中使用管道
<div>
  <p>货币金额: {{ amount | currencyFormat:'€': 'after': 3: '.' }}</p>
</div>

在上述代码中,amount 是组件中的货币数值,通过 currencyFormat 管道按照指定的货币符号()、符号位置(after)、小数位数(3)和千位分隔符(.)进行格式化显示。同时,管道通过缓存机制减少了重复计算。