7
votes

we are building new Angular 4 project and trying to understand what approach will be the best for handling global constants which will be reused through all project.

I want to place all constants inside shared folder like so

shared

  --constants
    --dateTime.ts
    --money.ts
    --dialogConfig.ts

and use injectable token for each file

https://blog.thoughtram.io/angular/2016/05/23/opaque-tokens-in-angular-2.html

for example dialogConfig.ts will be

export let DIALOG = new InjectionToken<DialogConfig>('dialog-config');

export const DIALOG_CONFIG: DialogConfig = {
 width : '600px',
 height : 'auto'
};

So that each constant object will be saved from name collision and will be injectable.

What will be proc and cons for this approach?

1
As a shared storage, localStorage is a better option and it is very easy to use. I don't know about the stuff you talking here. But try it if you fail here. Thanks - Viran Malaka
looks good to me - Poul Kruijt
Pros and cons in comparison to what? InjectionToken does what it does. If it's ok for you, it's ok. - Estus Flask
in comparison to any other approaches. Maybe someone was faced with drawbacks of using such approach? - VladosJS
WHy you can not just put constants to the files and use them ? Why you need injection token? - Sharikov Vladislav

1 Answers

2
votes

I am not sure if you might be over-complicating this by using Injection Tokens. If all you want to do is provide global constants across your app, you can fully control the namespaces of these constants and how you import them in each source file. By importing them from your specific constant-holding TS files, you can be absolutely sure to have no conflicts with other libraries.

You can easily avoid naming conflicts like that and I don't really see a reason for injecting constants using Angular's dependency management rather than just import them directly.

To me, the following approach seems more straight forward for your case:

  1. Define and export your constants in one or multiple TS files (as you do).
  2. Import the constants using import { MY_CONSTANT } from '../constants/my-constant.ts'; where ever you need them.
  3. Use them and be happy.