How to dynamically set API URL in Angular based on domain?

Discussão em 'Angular' iniciado por Zaid mone, Fevereiro 22, 2025.

  1. Zaid mone

    Zaid mone Guest

    I am working on an Angular 16 application that I deploy on IIS using Azure DevOps. The application is used by multiple clients, each with their own servers and domains.

    Problem: Currently, I define the API URL inside environment.ts, which requires me to rebuild and redeploy the app every time a client’s API URL changes. To make this dynamic, I created a config.json file in the assets/ folder, where I set all my clients' API URLs.

    What I Did: I deployed the config.json file with all the domain-specific API URLs. On the app startup, I fetch the config.json and set the API URL based on the client's domain. For example, in the environment.ts file, I added:

    - environment-production

    import config from '../assets/config.json';

    export const environment = {
    production: true,
    API_BaseURL: config.apiUrls.live
    };

    - environment

    import config from '../assets/config.json';

    export const environment = {
    production: true,
    API_BaseURL: config.apiUrls.live
    };


    The Issue: When I change the API URL in config.json on the server, the environment value does not update. I suspect this might be due to caching, as it doesn't change until I deploy a new release.

    My Question: How can I ensure that the config.json file is always fetched fresh, without being cached by the browser? Is there a better way to dynamically load the API URL based on the domain at runtime without needing to rebuild/redeploy the application?

    Continue reading...

Compartilhe esta Página