angulartypescriptproduction-environment

Access environment variables in production build Angular 4


I want to deploy a production build of angular app with a configurable API URL for the user to test it out. I use the environment.ts but after the production build, I do not know how to configure the variables.

What approach needs to be done?


Solution

  • Are you using Angular-CLI? It should be easy, then. You have something like this:

    src/
      app/
      environment/
        environment.ts
        environment.prod.ts
    

    Simply put different url in environment.prod.ts and your prod build gets a second url. E.g. let's say your environment.ts looks like this:

    {
      "production": false,
      "apiUrl": "http://localhost:8080"
    }
    

    Put this in environment.prod.ts:

    {
      "production": true,
      "apiUrl": "https://example.com/api"
    }
    

    You can setup more environments, check that section of .angular-cli.json and angular-cli repo.

    Edit: As per your comment, you want more.

    Yes but still this is not configurable after the build isn't it? Because I don't know what url the user want to use therefore I want to make it configurable from the outside after deploying the build.

    Let's continue this scenario further. Let's have a backend client:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { apiUrl } from '../environment/environment.ts';
    @Injectable()
    export class BackendService {
        backendUrl: string = apiUrl;      
    
        constructor(private httpClient: HttpClient) {}
    
        get(endpoint: string, params: any): Observable<any> {
          const url= `${this.backendUrl}/${endpoint}`;
          return this.httpClient.get(url, params);
        }
    }
    

    Simplified, but works. By default, you set your own URL. But your components can set the url on the fly, and get other things from that url.

    Now, the next step would be, offering which backends you have. This can be a preconfigured array, or you can let the client enter the url freely (simply input box). You can have a component that does that, and configures this service here. You should probably also have a separate service for your "proper" backend, where, e.g. your auth lies. But this all really depends on your scenario.