2016-09-26 3 views
14

저는 angi-cli에 익숙하지 않고 env에서 내 API 서비스 호출에 대한 URL을로드하려고합니다. 예 :angular2에 대한 angular-cli 환경 변수를로드하는 방법

local: http://127.0.0.1:5000 
dev: http://123.123.123.123:80 
prod: https://123.123.123.123:443 

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

그러나 angular2에서

, 내가 그렇게 전화를 어떻게 내가 API_URL를 얻을 수 있습니다 : environment.prod.ts

에 나는이 가정?

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

, 당신은 단지이 당신의 API를 URL을 얻으려면 : 당신의 프로젝트를 생성하여 각-CLI의 루트를 보면, 당신은 main.ts에서 볼 수

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()); 
     } 
    ); 
    } 

감사

답변

37

귀하의 서비스 헤더에서 동일한 작업을 수행 할 수 있습니다.

환경 경로는 환경 폴더와 관련된 서비스 위치에 따라 다릅니다. 나를 위해, 그것은 다음과 같이 작동합니다 :

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); 
    } 
} 
+2

그러나 그런 식으로 보일 수 있습니다 : '../../environments/environment'에서 가져 오기 {환경을}; 개발자 환경에 앱을 하드 코딩해야합니다. prod 환경 파일은 environment.prod.ts입니다. 만약 당신이 'ng build --prod'를한다면, ValuesService는 어떻게 environtment.prod에서 URL을 얻을 수 있습니까? – Pascal

+0

빌드 할 때 지정한 환경에 적합한 환경 파일이 패키지화됩니다. –

4

우리는 HttpClient 인터셉터를 사용할 수 있습니다. 이 방법의 장점은 API_URL의 가져 오기/삽입을 피하는 것이 API 호출이있는 모든 서비스입니다.

더 자세한 답변을 위해 당신은 여기 https://stackoverflow.com/a/45351690/6810805

관련 문제