16

To declare a constant file, I first create it in the same tree level as the component where the constant is used email.constants.ts and like this:

export class EmailConstants {

  public static MAXIMUM_NUMBER = 10;
}

And I import it that way from the controller:

import { EmailConstants } from './emails.constants';

Is this practice good? I ask the question here because I can not find the answer in the official guide style

Mouad Ennaciri
  • 1,217
  • 3
  • 15
  • 28

3 Answers3

45

I will do it like this:

export const MAXIMUM_NUMBER = 10;

and

import { MAXIMUM_NUMBER } from './emails.constants';

So only import what you use, not everything.

but if you still want to use everything, you can do it similarly as you have done, just change it a bit:

import * as EmailConstants from './emails.constants';

Then you can still use

EmailConstants.MAXIMUM_NUMBER
Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36
18

It is a good practice to make a separate file for your constants. Where, there could be multiple scenarios, in which I prefer/ recommend the Second one from the followings -

1) Export every constant & import as needed; if you don't have too many constants.

export const TEST = "testval";
export const TEST2 = "testval2";

Import as -

import { TEST, TEST2 } from './app.constants';

2) Create & export a single Injectable class if you have too many constants & want a hassle-free import.

So, your app.constants.ts would be -

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class AppConstants {
    public TEST = "testval";
    public TEST2 = "testval2";
}

Then, you could simply inject it in your required class like -

constructor(private constants: AppConstants) & use as - constants.TEST

3) You could also export an Object as -

export const constObj = {
    TEST: "testval",
    TEST2: "testval2"
};

And import it as -

import { constObj } from './app.constants'; & use as - constObj.TEST

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
0

Are you trying to avoid name collisions by "putting the file on the same tree level"? If so, consider Dependency Injection and Injection Tokens.

OliverE
  • 437
  • 5
  • 12