Is there a way to access the value of the --base-href parameter in my Angular project during the build process?

In my Angular project, I have set up multiple environments for different stages of development, testing, acceptance, and production. Each environment has a specific base URL, which I designate using the --base-href flag during the project build. However, I also need to connect to a second web server that also has its own set of DTAP stages. I am looking for a way to automatically determine which base URL flag is set so that I can assign the corresponding URL for the second web server in my code.

Despite my efforts to find information on this topic, I have not been successful in achieving the desired outcome. Currently, I manually update the variable value, but I want to eliminate this step as it is prone to oversight during project builds.

My goal is to implement the following code:

    let url;
    if (base-href.contains('test'))
        url = 'https://test.com';
    else if (base-href.contains('acceptance'))
        url = 'https://acceptance.com'
    else if (base-href.contains('deployment'))
        url = 'https://deployment.com'

    // Send API call to URL

The URLs I use for building are consistent, allowing me to predict their content and ensure correct assignment of the second web server URL.

If anyone can provide guidance on how to achieve this functionality, I would greatly appreciate it!

Answer №1

If you need to introduce another variable into your environment.ts file, simply add it there. This way, when you compile your code, that variable will be customized for each environment, allowing you to access it in your code.

export const environment = {
  production: true,
  host: 'test'
};

In your component:

import { environment } from '../environments/environment';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor() {}

  ngOnInit() {
    if (environment.host == 'test') {
      // do something
    }
  }

}
  • It's important to note that relying heavily on the environment variable may not be the best approach. This is because the code that works on one environment may not work on another due to the separate compilation for each environment.

A more efficient method would be to make an HTTP request when the application loads to retrieve configuration settings from a JSON file or database record stored on the server. This way, you can easily deploy your tested code to production without worrying about environment-specific variables.

For further information, you can refer to: Dave M Bush's article - where-to-store-angular-configurations

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage ngFor multiple times to iterate through the same array

As someone new to Angular and Ionic, I've scoured the internet (including this site) for a solution to my problem without much luck. My goal is to have a single array of tasks in my ts component and display them in four different sections of my html t ...

The Azure function application's automatic reload feature does not function properly with the v4 model

Struggling to get Azure Function to recognize and incorporate changes in source code. I have set up a launch task to initiate the local server and run an npm script with tsc -w in watch mode. While I can see the modifications reflected in the /dist folder ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...

Using HttpClient to post data to Django backend for seamless information transfer

Having trouble sending data from my Angular front end to my Django backend. I've triple-checked the code on the frontend... const post_data = { email: form.value.email, password: form.value.password } const headers = new HttpHeaders({ 'Con ...

What is the best way to utilize ngStyle in combination with Interpolation?

Within my application, I am faced with a challenge involving two slide bars that generate values ranging from 1 to 100. Based on these generated values, I aim to adjust the margin of a div element in accordance with the percentage output. Despite conductin ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Issues with FormsModule functioning incorrectly when used in a separate module other than the main App Module

Within my SharedModule, I have the FormsModule imported. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from &ap ...

a guide on accessing key value elements within an array using Ionic 3

Just diving into the world of Ionic, I am currently working on a task to showcase products on the cart page that have been added to the cart. Upon fetching data from a REST API, I can see the response below in the console. "items": { "29.2.2.0.YTowOnt ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Troubleshooting issue: matTooltip malfunctioning in *ngFor loop after invoking Angular's change

The matTooltip in the component below is rendering correctly. The overlay and small bubble for the tooltip are rendered, but the text is missing (even though it's present in the HTML when inspecting in the browser) and it isn't positioned correct ...

Error: The page you are trying to access does not have a valid default export. The provided type is not acceptable

Hello, I am a newcomer to the world of react and NextJS. Currently, I am working on a small project using NextJS 13 where I am attempting to display products stored in a JSON file (which will later be moved to a database). The application runs correctly, ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

Warning: Angular Compilation Issue - Deprecation Advisory

After upgrading to Angular 13, I've been encountering this deprecation warning. TypeError: message.trim is not a function at Function.Rule.FAILURE_STRING (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:30:81) at cb (/home/app/node_modules ...

Exploring the synergies between Angular 5 and atmosphere.js

I've been trying to incorporate atmosphere.js into my angular 5 project. So far, I've followed these steps: npm install --save @types/atmosphere.js npm install --save atmosphere.js In addition, I have set up a service as shown below: import { ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Is there a way to transfer data from a custom hook to a component seamlessly?

I am facing an issue with a custom hook that passes parameter data along with fetched data to the Settings component. Inside Settings, I have a hook called setData11 in useEffect and I am trying to set the data passed from useTable but encountering an er ...

Step-by-step guide on importing `block-ui`, `spectrum-colorpicker`, and `sass.js` libraries in a TypeScript project

I have been utilizing various plugins such as block-ui, spectrum-colorpicker, sass.js, etc., in my Angular 2 project written in TypeScript. Currently, I am loading these plugins directly in the index.html file. However, I would like to import them and onl ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...