22

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

Tampa
  • 75,446
  • 119
  • 278
  • 425

2 Answers2

47

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);
    }
}
Camille Laborde
  • 858
  • 11
  • 17
  • 3
    But that way: import { environment } from '../../environments/environment'; you hardcode your app to the dev environment. The prod environment file is called environment.prod.ts. What if you do 'ng build --prod' How can the ValuesService get the url from the environtment.prod ? – Pascal Dec 31 '17 at 12:02
  • 1
    When you build, the appropriate environment file gets packaged for the environment that you specify. – Chris Peacock Feb 13 '18 at 15:24
5

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

Mike Kovetsky
  • 1,638
  • 1
  • 14
  • 24