简体   繁体   中英

Best practice to store constants (in class v/s json object) in Angular 7

I want to store some constants which can be used through out the application.

export class DateTimeConstants {
  public static readonly DateFormat: string = 'dd/mm/yy';
  public static readonly DateTimeDisplayFormat: string =
    'dd/MM/yyyy hh:mm:ss aa';
  public static readonly TimeFormat: string = '12';
}

OR

export dateTimeConstants = {
  dateFormat: 'dd/mm/yy',
  dateTimeDisplayFormat: 'dd/MM/yyyy hh:mm:ss aa',
  timeFormat: '12'
}

Benefit of the first approach is that intellisense shows the fields name after putting dot(.) with class name while with second approach that is not available.

What should be the best practice as in future there are many more configuration to be added?

In my opinion the best practice to store some constraints(like configuration for DateTime, Date etc.) is exporting one constant with an assigned object(look at environment.ts file in every default Angular project)

I would transform your code into something like that:

export const dateTimeConstants = {
  dateFormat: 'dd/mm/yy';
  dateTimeDisplayFormat: 'dd/MM/yyyy hh:mm:ss aa';
  timeFormat: '12';
}

Intellisense helps after putting dot(.) and I think it's a good standard to be consistent with the angular application template/skeleton. This is my objective opinion :)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM