A Central Provider for Constants in Ionic 2

I’m not really sure what the best practice is in Angular 2 (and therefore Ionic 2) for defining your application’s constants in a central place but the question came up in the Ionic 2 forum yesterday.   I replied to the post with the method I have been using.  In my Ionic 2 apps I have a config.js file in the providers folder.

In this config.js file I export the constants like this:

export let SERVER_NAME = “myServer.com”;
export let TEST_USERNAME = “myName”;

(I suppose I could export a single object containing the values rather than exporting all the values individually but this is the way I have been doing this so far)

In any components that then need to reference a constant I do this:

import {SERVER_NAME) from ‘./config’;

and then I just use that value (in this case SERVER_NAME) whenever I need to in that component.

As I said, I have no idea really if this is considered best Angular 2 practice or whether or not there are any problems with it but so far it has worked for me.

 


I’m a mobile applications developer based in the UK, concentrating primarily on hybrid application development with Ionic and Ionic 2 but also with native development skills. Please visit www.crossplatformsolutions.co.uk for more information about me and how I may be able to help you with mobile application development, particularly with Ionic 2 but also with other mobile frameworks and technologies.  Thanks for visiting.

 

 

3 thoughts on “A Central Provider for Constants in Ionic 2

  1. Anish

    Can i change the value “TEST_USERNAME ” from another CLASS. I need to update the values of the constants. Is it possible

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s