1

I am working with an angular 2 project with typescript and webpack. At the development time I should use local APIs or test APIs. But when in production I should use the real APIs. So the API URL will changed.

APIs are used in many service files like product service etc.

I want to write all of my API URLs in a single file so that I can easily change the URLs when environment will changed.

How can I do it?

Md. Shougat Hossain
  • 501
  • 2
  • 8
  • 24

2 Answers2

3

You can create a config file and store your config values there as an object key-value.

config.ts:

export var config = {
  title: "Hello World",
  "SecurityService":"http://localhost/SecurityAPI",
  "CacheService":"http://localhost/CacheServiceAPI"
}

yourComponent.ts:

import { config } from './config';

myTitle = config.title;

Full example: http://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=info

You can also do an http request to your external config file (json);

Plunker: http://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=info

eko
  • 39,722
  • 10
  • 72
  • 98
2

You can create a TS class with static properties:

export class Environment {
   public static API_ENDPOINT = 'http://127.0.0.1:6666/api/';
}

Use it as following:

import { Environment } from './environment';

export class MyClass {
    apiEndpoint: string = Environment.API_ENDPOINT;
    ...
}

You can also create a const object:

export const environment = {
     API_ENDPOINT: 'http://127.0.0.1:6666/api/'
}

And use it like:

import { environment } from './environment';

export class MyClass {
    apiEndpoint: string = environment.API_ENDPOINT;
    ...
}
seidme
  • 12,543
  • 5
  • 36
  • 40