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

标签 angular angular2-cli

我是 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-cli for angular2 如何加载环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701389/

相关文章:

javascript - 类具有或正在使用外部模块中的名称 'SafeUrl' 但无法命名

angular2-cli - 找不到模块 './models/config'

angular - 没有数组的提供者

angular - 列表未按 Angular 更新

angular-cli - Angular CLI 安装失败

angular2-cli - 如何在使用angular-cli构建的angular2项目中包含Underscore.js

css - :host (body) not working in Angular

angular - CDK Drag Drop 无法正确更改图像的位置

typescript - 在 Typescript 中声明 JSON 对象的正确方法

css - angular2-cli 给出@multi 样式错误