Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining constants in typescript (ionic application)

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 ?

like image 889
runtimeZero Avatar asked Jun 16 '16 18:06

runtimeZero


People also ask

How to define constants in TypeScript?

Defining a constant in TypeScript can be pretty simple — you can just write something like const SOME_CONSTANT="FOO"; . However, that const keyword only works if you're defining variables at file-scope or inside a function.

How to maintain constants in TypeScript?

One way to manage constants in TypeScript is to use the class. In the following example, the AppSettings class is created with static properties to define constants. Those properties are applied with readonly modifiers, thus they can not be reassigned.

Is ionic TypeScript?

Since Ionic itself is written in TypeScript as well, editors can present all the methods available and what they expect as arguments. All the best IDE's available today have support for code completion, including VScode, Atom, WebStorm, Sublime text, and even command line editors, such as Vim/Neovim!


2 Answers

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;
like image 175
Gus Arik Avatar answered Oct 31 '22 16:10

Gus Arik


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

like image 38
Subhasish Nath Avatar answered Oct 31 '22 14:10

Subhasish Nath