【问题标题】:angular-cli for angular2 how to load environment variablesangular2的angular-cli如何加载环境变量
【发布时间】:2017-07-28 15:31:34
【问题描述】:

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


    【解决方案1】:

    如果您查看 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);
        }
    }
    

    【讨论】:

    • 但是这样: import { environment } from '../../environments/environment';您将您的应用程序硬编码到开发环境中。 prod 环境文件称为 environment.prod.ts。如果您执行“ng build --prod”怎么办 ValuesService 如何从 environtment.prod 获取 url?
    • 构建时,会为您指定的环境打包相应的环境文件。
    【解决方案2】:

    在 Angular 4.3 发布后,我们可以使用 HttpClient 拦截器。这种方法的优点是避免了 API_URL 的导入/注入是所有带有 api 调用的服务。

    更详细的答案可以看这里https://stackoverflow.com/a/45351690/6810805

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 2020-06-22
      • 2019-03-30
      • 1970-01-01
      • 2020-11-11
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多