angular2的angular-cli如何加载环境变量 [英] angular-cli for angular2 how to load environment variables
本文介绍了angular2的angular-cli如何加载环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是angular-cli的新手,并希望通过env为我的api服务调用加载url.例如
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
例如在environment.prod.ts
e.g. in environment.prod.ts
我认为这是
export const environment = {
production: true
"API_URL": "prod: https://123.123.123.123:443"
};
但是从angular2来说,我该如何调用才能获取API_URL?
But from angular2, how do I call so I can get 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中看到:
If you look at the root of your angular-cli's generated project, you will see in main.ts :
import { environment } from './environments/environment';
要获取您的api URL,只需在服务标头中执行相同的操作.
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);
}
}
这篇关于angular2的angular-cli如何加载环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文