Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular-cli for angular2 how to load environment variables

I am new to the angular-cli and want to load url's for my api service calls by env. E.g.

local: http://127.0.0.1:5000
dev: http://123.123.123.123:80
prod: https://123.123.123.123:443

e.g. in environment.prod.ts

I assume this:

export const environment = {
  production: true
  "API_URL": "prod: https://123.123.123.123:443"
};

But from angular2, how do I call so I can get API_URL?

e.g.

this.http.post(API_URL + '/auth', body, { headers: contentHeaders })
      .subscribe(
        response => {
          console.log(response.json().access_token);
          localStorage.setItem('id_token', response.json().access_token);
          this.router.navigate(['/dashboard']);
        },
        error => {
          alert(error.text());
          console.log(error.text());
        }
      );
  } 

Thanks

like image 671
Tampa Avatar asked Sep 26 '16 11:09

Tampa


People also ask

What is environment TS file in angular?

A project's src/environments/ folder contains the base configuration file, environment. ts , which provides a default environment. You can add override defaults for additional environments, such as production and staging, in target-specific configuration files. For example: myProject/src/environments.

Can we use process env in angular?

Short answer, no. When we execute a CLI command, CLI being a Node. js application, has access to all the system environment variables through process. env , however CLI when building our application does not provide this information to it.

How do you add an environment variable?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.


2 Answers

If you look at the root of your angular-cli's generated project, you will see in main.ts :

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

To get your api URL, you just have to do the same in your service header.

The path to environment is depending on the position of your service related to the environment folder. For me, it works like this :

import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';

@Injectable()
export class ValuesService {
    private valuesUrl = environment.apiBaseUrl + 'api/values';
    constructor(private http: Http) { }

    getValues(): Observable<string[]> {
        return this.http.get(this.valuesUrl)
        .map(this.extractData)
        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}
like image 55
Camille Laborde Avatar answered Oct 11 '22 14:10

Camille Laborde


After release of Angular 4.3 we have a possibility to use HttpClient interceprtors. The advantage of this method is avoiding of import/injection of API_URL is all services with api calls.

For more detailed answer you may look here https://stackoverflow.com/a/45351690/6810805

like image 40
Mike Kovetsky Avatar answered Oct 11 '22 14:10

Mike Kovetsky