【发布时间】:2018-07-23 13:59:27
【问题描述】:
如果在模板之外需要自定义 Angular 格式化/管道函数,那么 Angular 共享该函数的方式是什么?通过静态导出/导入还是通过InjectionToken?
选项 1:静态导出/导入
export myFormatter(value: string): string {
return ...
}
在服务中使用:
import { myFormatter } from 'my-formatter';
export class SomeService {
...
const formattedValue = myFormatter(value);
...
}
选项 2:InjectionToken
export const MY_FORMATTER = new InjectionToken('My Formatter', {
providedIn: 'root',
factory: () => (value: string) => { return ... }),
});
在服务中使用:
import { MY_FORMATTER } from 'my-formatter';
export class SomeService {
...
const myFormatter = this.injector.get(MY_FORMATTER);
const formattedValue = myFormatter(value);
...
}
我最初的直觉告诉我使用 InjectionToken 来利用 Angular 的依赖注入系统。另一方面,Angular exposes their formatting functions as of Angular 6 without the use of InjectionTokens。这就提出了一个问题,为什么 Angular 不将 DI 用于自己的格式化函数,我们应该如何共享这些函数?
【问题讨论】:
标签: angular angular-pipe