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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With