Angular-CLI for Angular2如何加载环境变量

2024-01-02

我是 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

例如在环境.prod.ts中

我假设是这样的:

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

但是从 Angular2 中,我如何调用才能获得 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


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

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

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

环境的路径取决于与环境文件夹相关的服务的位置。对我来说,它的工作原理如下:

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);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular-CLI for Angular2如何加载环境变量 的相关文章

随机推荐