I am currently using proxy.conf.json to configure API url for development. I believe it only works on the local server. How can I configure the API url when deploying it on UAT and Production server? I would like to change the API url on the server without re-building the entire application.
proxy.conf.json:
{
"/api": {
"target": "http://api_server:88",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
api.service.ts:
get<T>(params: any = {}) : Observable<T> {
return this.http.get<T>("/api/data", {params: params});
}
This way has been working great for us:
custom-http.service.ts <- You can name this specific to your company / app name
@Injectable()
export class CustomHttpService {
constructor(private http: HttpClient) {
}
public getCurrentEnvironment(): string {
const host = window.location.origin;
let env = "";
switch(host) {
case 'http://localhost:4200': {
env = 'LOCALDEV';
break;
}
case 'https://my-test-site.azurewebsites.net': {
env = 'TEST';
break;
}
case 'https://my-prod-site.azurewebsites.net': {
env = 'PROD';
break;
}
case 'https://customdomain.com': {
env = 'PROD';
break;
}
default: {
env = 'PROD';
break;
}
}
return env;
}
public get(url: string): Observable<any> {
return this.http.get(url);
}
public getWithHeader(url: string, header: HttpHeaders): Observable<any> {
return this.http.get(url, {headers: header});
}
public post(url: string, body: any): Observable<any> {
return this.http.post(url, body);
}
public put(url: string, body: any): Observable<any> {
return this.http.put(url, body);
}
public delete(url: string): Observable<any> {
return this.http.delete(url);
}
}
You can call getCurrentEnvironment() from any where in your app to know which environment you are on.
@Injectable()
export class URLHelper {
constructor(private httpService: CustomHttpService) {
}
private env: string = this.httpService.getCurrentEnvironment();
private Server: string = this.getServerUrl(this.env);
getServerUrl(env: string): string {
let server = "";
switch (env) {
case "LOCALDEV": {
server = "http://localhost/project/";
break;
}
case "TEST": {
server = "https://my-test-site-api.azurewebsites.net/";
break;
}
case "PROD": {
server = "https://my-prod-site-api.azurewebsites.net/";
break;
}
default: {
console.error('No Env Found');
server = "https://my-prod-site-api.azurewebsites.net/";
}
}
return server;
}
// Here you will define all the API endpoints your app will use and 'this.Server ' will contain the proper host API server url at runtime for each environment.
public User = this.Server + 'api/User';
@Injectable()
export class AdminService {
constructor(private urlHelper: URLHelper, private httpService: CustomHttpService) { }
getUser(): Observable<any> {
return this.httpService.get(this.urlHelper.User);
}
}