面试题答案
一键面试实现思路
- 创建自定义管道类:使用Angular CLI生成一个新的管道类,在类中实现
transform
方法来处理货币转换逻辑。 - 处理常规货币格式:利用JavaScript的
Intl.NumberFormat
对象来格式化货币,这是处理常规货币格式的标准方式。 - 添加特定前缀:在格式化后的货币字符串前添加指定的前缀。
- 处理负数显示:在
transform
方法中判断数值是否为负数,如果是负数,则添加特定的CSS类来改变颜色。
关键代码片段
- 创建管道:
ng generate pipe customCurrency
- 自定义管道代码(custom - currency.pipe.ts):
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'customCurrency' }) export class CustomCurrencyPipe implements PipeTransform { transform(value: number, prefix: string = ''): string { let currencyFormat = new Intl.NumberFormat('en - US', { style: 'currency', currency: 'USD' }); let formattedValue = currencyFormat.format(value); if (value < 0) { return `<span class="negative - currency">${prefix}${formattedValue}</span>`; } return `${prefix}${formattedValue}`; } }
- 在组件模板中使用管道:
<div> <p>{{ 100 | customCurrency: 'CompanyX - ' }}</p> <p>{{ -50 | customCurrency: 'CompanyX - ' }}</p> </div>
- 添加CSS样式(styles.css):
.negative - currency { color: red; }
### 测试自定义管道的方法
1. **单元测试**:
- 利用Jest或Karma等测试框架来测试管道。
- 在`custom - currency.pipe.spec.ts`文件中编写测试用例。
- 示例(使用Jest):
```typescript
import { CustomCurrencyPipe } from './custom - currency.pipe';
describe('CustomCurrencyPipe', () => {
let pipe: CustomCurrencyPipe;
beforeEach(() => {
pipe = new CustomCurrencyPipe();
});
it('should add prefix to positive value', () => {
const result = pipe.transform(100, 'CompanyX - ');
expect(result).toContain('CompanyX - $100.00');
});
it('should add prefix and negative class to negative value', () => {
const result = pipe.transform(-50, 'CompanyX - ');
expect(result).toContain('CompanyX - $-50.00');
expect(result).toContain('negative - currency');
});
});
- 集成测试:
- 创建一个简单的组件来使用该管道,并在组件的模板中添加不同的数值进行测试。
- 确保管道在实际应用场景下能正确工作,如在不同组件中传递不同的货币数值并检查显示效果。
通过以上步骤,可以实现一个满足需求的自定义货币转换管道,并对其进行有效的测试。