Angular中的内置管道典型作用就是用来格式化数据,举一个最简单的例子。
<p>My birthday is {{ birthday | date }}</p>
<p>My birthday is {{ birthday | date:"MM/dd/yy" }} </p>
export class AppComponent {
birthday = new Date(2021, 4, 20);
// 需要注意这里的月份要写4而不是5,因为月份是从零开始计数的
}
打印结果如下:
My birthday is May 20, 2021
My birthday is 05/20/21
Angular中内置了12个管道指令,他们分别是:
- AsyncPipe
- DatePipe
- I18nPluralPipe
- I18nSelectPipe
- JsonPipe
- LowerCasePipe
- CurrencyPipe
- DecimalPipe
- PercentPipe
- SlicePipe
- UpperCasePipe
- TitleCasePipe
对于国际化开发者来说,咋一看应该是绝对够用的了,那么笔者为何还要不遗余力的推荐Singleton这样的国际化开发开源库呢?它的优势何在?让我试着为您娓娓道来。
Date
先来关注出镜率最高的date pipe,内置管道的写法和打印效果如下表(这里我们以ja-JP为例)。PS. 切记在使用国际化pipe前,要import并注册locales data,否则无论用户如何切换语言,App永远只显示英文格式(这样的bug笔者已经不止一次遇到,当然如果我们需要支持100个locale,就需要注册100遍,会直接导致bundle变得超级大,从而引发性能问题)。
import ja from '@angular/common/locales/ja';
registerLocaleData(ja, 'ja');
随后还需要在provider中明示LOCALE_ID,示意代码如下:
…
providers: [
{ provide: LOCALE_ID, useValue: 'ja' }
],
…
{{ date | date: 'fullTime' }} | 12時34分56秒 GMT-04:00 |
{{ date | date: 'fullDate' }} | 2021年5月20日木曜日 |
{{ date | date: 'full' }} | 2021年5月20日木曜日 12時34分56秒 GMT-04:00 |
再来对比Singleton的写法和显示效果。首先在constructor中设置当前App的locale。
constructor(public i18nService: I18nService, public localeService: LocaleService) {
…
this.localeService.setCurrentLocale(this.locale);
…
}
{{ date | dateFormat: 'fullTime'}} | 12時34分56秒 GMT-04:00 |
{{ date | dateFormat: 'fullDate'}} | 2021年5月20日木曜日 |
{{ date | dateFormat: 'full'}} | 2021年5月20日木曜日 12時34分56秒 GMT-04:00 |
Currency
内置管道的写法和打印效果如下表(这里我们以使用了人民币,日元和欧元在locale分别为fr,it和ja时为例)。
// fr {{ num | currency:'CNY' }}</div> {{ num | currency:'JPY' }} {{ num | currency:'EUR' }} | 1 234 560,79 CNY 1 234 561 JPY 1 234 560,79 € |
// it | 1.234.560,79 CN¥ 1.234.561 JPY 1.234.560,79 € |
// ja | 元1,234,560.79 ¥1,234,561 €1,234,560.79 |
对比Singleton的写法和显示效果。
// fr {{ num | currencyFormat: 'CNY' }} {{ num | currencyFormat: 'JPY' }} {{ num | currencyFormat: 'EUR' }} | 1 234 560,79 CNY 1 234 561 JPY 1 234 560,79 € |
// it | 1.234.560,79 CN¥ 1.234.561 JPY 1.234.560,79 € |
// ja | 元1,234,560.79 ¥1,234,561 €1,234,560.79 |
Percentage
内置管道的写法和打印效果如下表(这里我们以使用了it,de和ja为例)。
// it {{ pi | percent }} {{ pi | percent : '0.1-2' }} | 31% 31,42% |
// de | 31 % 31,42 % |
// ja | 31% 31.42% |
对比Singleton的写法和显示效果。
// it {{ pi | percentFormat }} {{ pi | percentFormat: { minFractionDigits: 2 } }} | 31% 31,42% |
// de | 31 % 31,42 % |
// ja | 31% 31.42% |
总结
经过对比发现,Singleton可以有效规避需要同时注册多个locale而引发的bundle过大,以及带来的性能问题;关于国际化L2相关API支持的参数更加丰富,做出相应扩展的同时还使之更加的易用;Singleton采用了CLDR作为其数据格式源,也更加的规范和标准化;另外Singleton对L2的pipe做出了性能优化(测试数据会在随后的文章中贴出),还提供了相对时间的计算和显示方式,这些都是原生Angular管道所不具备的。