How to config different development environment in Angular 2 app

Viewed 52249

I have a constant file

export class constants {
    public static get API_ENDPOINT(): string { return 'https://dvelopment-server/'; }
}

And I imported it to my service

private _registrationUrl = constants.API_ENDPOINT+'api/v1/register';

How can I change the endpont with server change . I have development server staging server and local server. I want app to detect the environment change.

In my angular 1 app I used envserviceprovider for this. Can I use the same in angular 2 app ?

6 Answers

@cartucho's answer works great until you try to deploy to multiple environments with services like Heroku or Github actions. These services make it easy to use node environment variables, but do not have a way configure environment specific build commands.

One way to solve this is to set your Angular environment variables up like @cartucho suggested, then set your build script to call a small node application. The node application reads a node environment variable and then decides which build command to run.

In package.json: "build": "node build-app.js",

build-app.js:

const { exec } = require('child_process');

let buildScript = 'ng build --configuration=staging';
if (process.env.ANGULAR_ENVIRONMENT_CONFIGURATION === 'production') {
    buildScript = 'ng build --configuration=production';
}
const child = exec(buildScript, function (err, stdout, stderr) {
    if (err) throw err;
    else console.info(stdout);
});

child.stdout.on('data', function (data) {
    process.stdout.write(data);
});

child.stderr.on('data', function (data) {
    process.stdout.write(data);
});

child.on('exit', function (data) {
    process.stdout.write("I'm done!");
});

I go into more detail and talk about additional steps required for Angular Universal in my blog post: https://dev.to/jfbloom22/a-better-way-to-deploy-angular-universal-to-multiple-environments-206j

Related