Tam*_*mpa 19 angular2-cli angular
我是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
Run Code Online (Sandbox Code Playgroud)
例如在environment.prod.ts中
我假设这个:
export const environment = {
production: true
"API_URL": "prod: https://123.123.123.123:443"
};
Run Code Online (Sandbox Code Playgroud)
但是从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());
}
);
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Cam*_*rde 45
如果你看一下angular-cli生成的项目的根,你会在main.ts中看到:
import { environment } from './environments/environment';
Run Code Online (Sandbox Code Playgroud)
要获取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);
}
}
Run Code Online (Sandbox Code Playgroud)
在Angular 4.3发布后,我们有可能使用HttpClient拦截器.这种方法的优点是避免导入/注入API_URL是api调用的所有服务.
有关更详细的答案,请访问/sf/answers/3174618331/
| 归档时间: |
|
| 查看次数: |
21977 次 |
| 最近记录: |