0

We have a file in an application which resides in enter image description here

this file contains all constant, service URL which is used in all over the application. Now my problem is when our environment is changing from development to QA or to Production, we need to change on this file.

Do we have any approach to handle this in angular 2+? by creating a separate constant file for environment specific?

1

2 Answers 2

0

If you are using angular CLI then you'll have two file environment.ts and environment.prod.ts. You can user these files to store your constants. In normal build environment.ts is used. But when you create build with

ng build --prod

environment.prod.ts will be used in this case

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Point is, do we need to copy all url in these files? If yes, In that case we need to change whole application where we are importing app constant file
If that's your case you can follow below approach: 1. import your constants to these environement.ts files.. 2. import this environment file in your app.constants.ts and then export it in the required type so that you don't have to change anywhere else in your code.
0

For config files I found a tutorial long time ago (but works with ".json" files)

import { Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class ArchConfigurationService {
    private config: Object = null;
    private env:    Object = null;

  constructor (
    private http: Http,
  ) { }

    /**
    * Permite recuperar una propiedad en concreto.
    * Normalmente será una string, pero tambien puede ser un objeto
    * @param key La propiedad a buscar en la configuración.
    */
    public getProperty(key: string): any {
        return this.config[key];
    }

    /**
     * Obtain the env.
     */
    public getEnv(): string {
        return this.env['env'];
    }

    /**
     * Loads the "env.json" to obtain the env (Ej: 'production', 'development' )
     *  Then for this env loads the "[env].config.json"  (Ej: 'development.config.json')
     */
    public load() {
        return new Promise((resolve, reject) => {
            this.http.get('./enviroments/env.json')
            .map( res => res.json() )
            .catch((error: any):any => {
                console.log('Configuration file "env.json" could not be read');
                resolve(true);
                return Observable.throw(error || 'Server error');
            }).subscribe( (envResponse) => {
                this.env = envResponse;
                let request:any = null;
                let enviro = this.getEnv();
                switch (enviro) {
                    case 'production': 
                        request = this.http.get('/enviroments/' + enviro + '.config.json');
                    break;

                    case 'development': 
                        request = this.http.get('./enviroments/' + enviro + '.config.json');
                    break;

                    default: 
                        console.error('Environment file is not set or invalid');
                        resolve(true);
                    break;
                }
                if (request) {
                    request
                        .map( (res: any) => res.json() )
                        .catch((error: any) => {
                            console.error('Error reading ' + enviro + ' configuration file');
                            resolve(error);
                            return Observable.throw(error || 'Server error');
                        })
                        .subscribe((responseData: any) => {
                            this.config = responseData;
                            resolve(true);
                        });
                } else {
                    console.error('Env config file "env.json" is not valid');
                    resolve(true);
                }
            });

        });
    }
  }

The env.json

{
  "env": "development"
}

And the development.config.json

{
   "url": ...
}

And if you want to use in the app load (otherwise use "load")

import { ArchConfigurationService } from './services/arch.configuration.service';

providers: [
    ArchConfigurationService,
    { provide: APP_INITIALIZER, useFactory: (config: ArchConfigurationService) => () => config.load(), deps: [ArchConfigurationService], multi: true },
 ...

Comments

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.