代码之家  ›  专栏  ›  技术社区  ›  Sam Herrmann

在模板外共享自定义角度格式函数

  •  0
  • Sam Herrmann  · 技术社区  · 8 年前

    如果模板外部需要自定义角度格式/管道函数,那么共享该函数的角度方式是什么?通过静态导出/导入或通过 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用于它们自己的格式化函数,我们应该如何共享这些函数?

    1 回复  |  直到 8 年前
        1
  •  0
  •   user4676340user4676340    8 年前

    不要依赖于Angular,因为它将使用复杂的函数在不同的特性之间共享代码。

    相反,请考虑依赖Typescript,通过生成一个可导出函数:

    export function myFormatter(value: string): string {
      return ...
    }
    

    在你的特征中:

    import { myFormatter } from 'path/to/file';
    
    export class MyComponent {
      myFormatter = myFormatter;
    }
    

    您还可以从中创建一个超级类:

    export class FormatterUtils {
      myFormatter(value: string): string {
        return ...
      }
    }
    

    在你的特征中

    import { FormatterUtils } from 'path/to/file';
    
    export class MyComponent extends FormatterUtils {
      constructor() { super(); }
    }
    
    推荐文章