2016-09-26 26 views
14

Açısal kısma yeni ve url'leri env. Örneğin.angular2 angular-cli ortam değişkenleri nasıl yüklenir

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

ör

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

Ama angular2 dan

, çok diyorsunuz nasıl API_URL alabilirsiniz: environment.prod.ts

ben bu varsayıyorum?

örn.

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

, sadece var senin api URL almak için: projesini oluşturulan senin açısal-cli kökünde bakarsanız, main.ts göreceğiniz

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

Teşekkür

cevap

37

Servis başlığınızda aynı şeyi yapmak.

Çevreye olan yol, hizmetinizin ortam klasörüyle ilişkili durumuna bağlıdır. Benim için, bu gibi çalışır: Biz HttpClient interceprtors kullanmak için bir olasılık var

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

Ama bu şekilde görünebilir: '../../environments/environment' dan ithal {ortamı}; , uygulamanızı dev ortamına sabitlersiniz. Prod çevre dosyasına environment.prod.ts denir. Ne yaparsan yap --prod 'ValuesService environtment.prod' dan url'yi nasıl alabilir? – Pascal

+0

Oluşturduğunuzda, uygun ortam dosyası belirttiğiniz ortam için paketlenir. –

4

Açısal 4.3 kullanıma sunulduktan sonra. Bu yöntemin avantajı API_URL'nin içe aktarılması/enjekte edilmesinin api çağrıları ile gerçekleştirilmesidir.

daha detaylı cevap için burada https://stackoverflow.com/a/45351690/6810805

İlgili konular