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 ?

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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
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

1 Comment

I wish you could elaborate more as to where you add this code. Inside what file?
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 :)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.