10

In my Ionic application I am defining constants as

//constants.ts
export var CONSTANTS = {
 API_ENDPOINT: 'http://localhost:3000/'
};

and importing it as

import {CONSTANTS} from '../../services/constants'; //the path is correct

However I get the error CONSTANTS not defined in the file where I am importing.. what am i missing here ?

runtimeZero
  • 26,466
  • 27
  • 73
  • 126

4 Answers4

23

Here is how you should do it:

// constants.ts
export const API_ENDPOINT= 'http://localhost:3000/';

And importing it as:

import * as Constants from '../../services/constants';

And you can access it like this:

Constants.API_ENDPOINT;
Community
  • 1
  • 1
Gus Arik
  • 349
  • 2
  • 14
  • 2
    what about if i want to create multiple variables in constant.ts? 1. where do i put it in the project structure 2. how to access single variable from it thank you – George Dec 20 '17 at 23:31
1

For Ionic

app.value('config', {
  "constant1": "value1",
  "constant2": "value2"
});

and access it with

config.constant1

Do not forget to inject dependency config.

For Nativescript

Define

var configObject = {
    testData: false,
    apiUrl: "https://www.domain.com/api/v1/"
};

Use

var config = require('../../utils/config');

and get value

config.apiUrl

Regards

Hardik Vaghani
  • 2,163
  • 24
  • 46
1

In my App I created my constant file like bellow,in my main directory of my app inside filename - "envrionment.ts"

export const environment = {
  site_url : 'http://localhost/wp',
  quotes_url : '/wp-json/wp/v2/quotes',
  jwt_url: '/wp-json/jwt-auth/v1/token'
}

Then I imported from inside my provider like bellow:

import {environment} from '../../envrionment';

Hope it helps, Thanks :)

Subhasish Nath
  • 124
  • 1
  • 14
0

However I get the error CONSTANTS not defined in the file where I am importing

It works fine. Double check:

  • tsconfig.json : have module setting set.
  • console.log(CONSTANTS) in both files to see whats happening
basarat
  • 261,912
  • 58
  • 460
  • 511