1

I'm regularly running a project locally with two different configurations. One with stubbed data, one connected to the Spring Boot backend. I can switch between these modes with the below logic by making connectToBackend=true.

// Angular 11, src/environments/environment.ts

import processStubs from '[REDACTED]';
import processBackend from '[REDACTED]';
import { Launcher } from '[REDACTED]';

let connectToBackend = false;

let processLocal;
if (connectToBackend) {
  processLocal = processBackend;
} else {
  processLocal = processStubs;
}

export const environment = {
  process: processLocal,
  launcher: Launcher,
  production: false,
  backendConnection: connectToBackend,
};

How can I make connectToBackend a dynamic variable that is set by the command line when serving the project? For example:

ng serve --connectToBackend=true
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Otto
  • 45
  • 1
  • 6
  • 2
    Why not just make it _two environments_? – jonrsharpe Aug 12 '21 at 12:56
  • environment.prod.ts is already in use. I think you can add to the list of custom environments in the angular.json, but I was not able to get that to work with 'ng serve --...'. – Otto Aug 12 '21 at 12:59
  • It's unclear what exactly you did, but if you follow the guidance at e.g. https://angular.io/guide/build that should work. If not, give a [mre]. It's certainly going to be easier than trying to add custom arguments. – jonrsharpe Aug 12 '21 at 13:01
  • You can create other environments, check: https://itnext.io/multi-environment-setup-for-your-angular-app-a211d72f1ff1 https://angular.io/guide/workspace-config#alternate-build-configurations – Hoch Aug 12 '21 at 13:01
  • Thank you both and Arutsudar for the answer below. The multi-environments solution is the way to go and works fine for ng serve now. I was missing the config under "serve" in angular.json. – Otto Aug 12 '21 at 13:38

1 Answers1

3

The ng serve command accepts the parameter configuration.

You can have multiple environments in angular (as also suggested by others in comments).

In angular.json you can mention a new environment configuration that can overwrite the default environment file. (Referred from Link)

"build": {
  "configurations": {
    "production": {
      // ...
    },
    "demo": {
      "fileReplacements": [
        {
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.demo.ts"
        }
      ]
    }
  }
}

"serve": {
  "configurations": {
    "production": {
      // ...
    },
    "demo": {
      "browserTarget": "PROJECTNAME:build:demo"
    }
  }
}

Create a new file src/environments/environment.demo.ts to store the value of backendConnection variable (along with other necessary variables)

export const environment = {
  process,
  launcher: Launcher,
  production: false,
  backendConnection: true
};

For running the new environment, you can use a command like this ng serve -c=demo.

Arutsudar Arut
  • 195
  • 1
  • 13