angular-cli for angular2如何加载环境变量

angular-cli for angular2 how to load environment variables

我是 angular-cli 的新手,想通过 env 为我的 api 服务调用加载 url。例如

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

例如在 environment.prod.ts

我假设是这样的:

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

但是从 angular2 开始,我该如何调用才能得到 API_URL?

例如

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());
        }
      );
  } 

谢谢

如果您查看 angular-cli 生成的项目的根目录,您将在 main.ts 中看到:

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

要获得您的 api URL,您只需在服务 header 中执行相同的操作即可。

环境路径取决于您的服务与环境文件夹相关的位置。对我来说,它是这样工作的:

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);
    }
}

在 Angular 4.3 发布后,我们有可能使用 HttpClient 拦截器。这种方法的优点是避免了 import/injection of API_URL is all services with api calls.

更详细的答案可以看这里