Home > Software engineering >  Environment: How to make apiBaseUrl dynamic?
Environment: How to make apiBaseUrl dynamic?

Time:10-08

If my application is on production mode, I want the base URL of my API to be https://example.com/. If not, it should be http://localhost:8080/.

environment.prod.ts

export const environment = {
  production: true,
  apiBaseUrl: 'https://example.com/'
};

environment.ts

export const environment = {
  production: false,
  apiBaseUrl: 'http://localhost:8080/'
};

Now if I use environment in my service, it asks me to import either ../environment/environment or ../environments/environment.prod.

How can I make it to import the one which is needed? If production mode, import environment.prod, if not, import environment.

CodePudding user response:

in angular.json you have this section

    "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],

this is doing the job for you

CodePudding user response:

If my application needs to be deploy on production server then we need to environment.prod.ts and if you need only for testing or work on local system then you need to environment.ts.

And both file should be keep under the environment folder and we can define BaseUrl for calling the api

For Environment.prod.ts

export const environment = {
  production: true,
  apiBaseUrl: 'https://example.com/'
};

here you can see when you need for production server you need production key should be true otherwise you can keep with false

For environment.ts

export const environment = {
  production: false,
  apiBaseUrl: 'http://localhost:8080/'
};

environment.ts is basically use for local environment so here you should put production key as false.

Good Luck

  • Related