8

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.

1 Answer 1

6

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

5 Comments

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!
you can store your api url in environment file and pass the environment name during ng build
see the sample environment variable
@user3786798 : I have updated my answer according to your need
Where do you put various access keys and stuff you don't want in the codebase?

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.