在Angular中何处放置独立函数

所以我有这些功能,它们正由3个组件使用。

放在哪里合适的位置?

我当时想像在红宝石上。他们有lib,但是我不确定这些方法在lib文件夹中是否可以使用。

当前位于src/helpers/upload-file-helpers.ts

export function fileSizeConverter(size: number,fromUnit: string,toUnit: string ): number | string {
  const units: string[] = ['B','KB','MB','GB','TB'];
  const from = units.indexOf(fromUnit.toUpperCase());
  const to = units.indexOf(toUnit.toUpperCase());
  const BASE_SIZE = 1024;
  let result: number | string = 0;

  if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }

  result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);

  return result.toFixed(2);
}
export function isFileMoreThanLimit(fileSize: number,toUnit: string,limit: number) {
  return fileSizeConverter(fileSize,fromUnit,toUnit) > limit;
}
export function fileExtensionChecker(file: string): boolean {
  const fileExtensions = {
    'png' : true,'jpg' : true,'jpeg': true,'stl' : true,'obj' : true,'zip' : true,'dcm' : true,'3oxz': true
  };
  // this is weird,instead of showing undefined if file argument is not present in the hash it will throw error.
  return fileExtensions[file] ? true : false;
}
export function fileTypeParser(fileType: string): string {
  return fileType.split('/')[1];
}

此外,我故意不想将它们放在一个类中。这只是被单独调用。

a119919756 回答:在Angular中何处放置独立函数

使用TypeScript编写实用程序功能的主要方法有两种:

A)正常功能(分组​​在文件中)

util.ts

export function sum(a: number,b: number): number {
    return a + b;
}

export const sum = (a: number,b: number): number=> {
    return a + b;
};

用法

import { sum } from './util';
...
let value = sum(4,11);

B)类的静态方法

export class Math {
    static sum(a: number,b: number): number {
        return a + b;
    }
}

参考

Utilities in TypeScript

Utility class

本文链接:https://www.f2er.com/3019088.html

大家都在问