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
Constant are like services in AngularJS in which we can define our globally data. It is declare using "constant" keyword. As we define our app-keys in Web.
Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared.
Even if constants are related, they should not be put into a single file. The wrapper classes in Java is a good example of related constants being defined in their own class files rather than in a WrapperConstants file.
One way to manage constants in TypeScript is to use the class. In the following example, the AppSettings class is created with static properties to define constants. Those properties are applied with readonly modifiers, thus they can not be reassigned.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With