I was wondering if there was any way in Angular 2+ that I could have my api url's in some external config.json file and load them prior to build. I ask this because in my current situation I am just defining them as variables in my service and if I want to make changes to the URL's I must manually change the code and rebuild. With this config file I was thinking of defining them there so that if I change the config properties, I would not have to rebuild the code each time I do so.
Asked
Active
Viewed 1.3k times
1 Answers
5
The new angular-cli have the concept of different environments like development (dev) and production (prod).
When creating a new application with the cli ng my-app and /environments folder is a part of the scaffold which contains the environment files.
├── environment.ts
├── environment.prod.ts
When the application is built (ng build) or served (ng serve), the environment.{env}.ts file from /environments is pulled and replaces the file within /src/app. By default this is dev.
In order to grab the production version, set the environment to production using the following:
#build
$ ng build --environment=production
#shorthand
$ ng b -prod
#serve
$ ng serve --environment=production
#shorthand
$ ng s -prod
SAMPLE ENV FILE
export const environment = {
production: false,
envName: 'qa'
};
Read more about ng build command here
EXAMPLE
export const environment = {
production: false,
apiUrl: 'http://example.com/api'
};
app.component
import { Component } from '@angular/core';
import { environment } from './environment';
@Component({
moduleId: module.id,
selector: 'myapp-app',
templateUrl: 'myapp.component.html',
styleUrls: ['myapp.component.css']
})
export class MyappAppComponent {
title = 'myapp works!';
environmentName = environment.apiUrl;
}
template
<h1>
{{title}}
</h1>
<h2>
{{environmentName}}
</h2>

santosh singh
- 27,666
- 26
- 83
- 129
-
thanks, so I looked into the eviorments.ts files including prod, and was wondering is it in these enviorment.ts file where I would store the variables that would hold my api url"s? Also how would I link these eviorment variables to my service? Thanks for your help! – user3786798 Dec 28 '17 at 17:38
-
you can store your api url in environment file and pass the environment name during ng build – santosh singh Dec 28 '17 at 17:39
-
see the sample environment variable – santosh singh Dec 28 '17 at 17:40
-
@user3786798 : I have updated my answer according to your need – santosh singh Dec 28 '17 at 17:44
-
1Where do you put various access keys and stuff you don't want in the codebase? – f.khantsis May 01 '19 at 18:15