Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using injectable token for handling global constants Angular 4

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?

like image 818
VladosJS Avatar asked Jul 12 '17 15:07

VladosJS


1 Answers

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.
like image 106
fjc Avatar answered Oct 03 '22 01:10

fjc