You can try something like this, Create file appConfig.service.ts in root component.
import { Injectable } from "@angular/core";
interface EndPoint {
baseUrl: string;
requiresAuthentication: boolean;
}
interface ResourceLocator {
[key: string]: EndPoint;
}
interface XResourceLocator {
x: ResourceLocator;
}
interface YResourceLocator {
y: ResourceLocator;
}
@Injectable()
export class APIConfigurations implements XResourceLocator, YResourceLocator {
private _config;
constructor() {
this._config = require("./apiConfig.json");
}
public get x(): ResourceLocator {
return this.clone(this._config.x);
}
public get y(): ResourceLocator {
return this.clone(this._config.y);
}
private clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
}
and then define your all urls in apiConfig.json:
{
"x": {
"apiary": {
"baseUrl": "https://private-xyz.apiary-mock.com/test/",
"requiresAuthentication": false
},
"local": {
"baseUrl": "http://localhost:8080/test/",
"requiresAuthentication": false
}
},
"y": {
"apiary": {
"baseUrl": "https://private-xyz.apiary-mock.com/test1/",
"requiresAuthentication": false
},
"local": {
"baseUrl": "http://localhost:8080/test1/",
"requiresAuthentication": false
}
}
}
So you can define any baseUrl based on the environment here.
And use this in your any service.ts file:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {APIConfigurations} from "../app/apiconfig.service";
import 'rxjs/Rx';
@Injectable()
export class DashboardService {
private _requestOptions: RequestOptions;
private _baseUrl: string;
constructor(private http: Http, apiConfigs: APIConfigurations) {
const headers = new Headers({ 'Accept': 'application/json' });
const config = apiConfigs.x["local"];
this._baseUrl = config.baseUrl;
this._requestOptions = new RequestOptions({ headers: headers, withCredentials: config.requiresAuthentication });
}
/**
* [getUsers list of users]
*/
getUsers() {
return this.http.get(this.resolveUrl(`users`), this._requestOptions)
.map(res => res.json())
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
public resolveUrl(path: string): string {
var normalized = this._baseUrl.endsWith("/")
? this._baseUrl
: this._baseUrl + "/";
return normalized + path;
}
}
Hope this will help you.