I have an angular service which reads a json file containing a rest fqdn and rest port ({ "restFqdn":"kuno.dev.net", "restPort":"58085" }). I want share the fqdn and port with all other http services, which get json data from a backend rest server. The fqdn and port are static after being read from the json file, but the json file can contain different values for a particular deployment.
@Injectable()
export class FileService {
private result: Object;
private restFqdn = '';
private restPort = '';
constructor(private http:Http) {
this.result = this.getConfFile();
console.log('FileService - constructor: ', this.result)
this.setFqdn(this.result[0]);
this.setPort(this.result[1]);
}
getConfFile() {
return this.http.get('json/conf.json')
.map( (res:Response) => {
this.result = res.json();
console.log('FileService - getConfFile(): ', this.result)
return this.result;
}
)
.catch( error =>
Observable.throw(error || 'Server error')
);
};
setFqdn(value) {
this.restFqdn = value;
console.log('FileService - setFqdn(): ', this.restFqdn);
}
getFqdn() {
return this.restFqdn;
}
I am not sure how to share the fqdn and port with my services. I don't really think this is state information, but do I try and use an external library like ngrx/store to do this or is there some other approach that works? This is what I currently have in my RateService.ts:
constructor(private _http: HttpClient, private _fileService: FileService) {
this._fileService.getConfFile().subscribe (
data => {
this.restFqdn = data.restFqdn;
this.restPort = data.restPort;
this.rateApi = '/kuno/rate';
this.rateUrl = 'http://' + this.restFqdn + ':' + this.restPort + this.rateApi;
console.log('RateService - constructor() - restFqdn: ', this.restFqdn);
console.log('RateService - constructor() - restPort: ', this.restPort);
},
err => {
this.errorMessage = 'Error - getConfFile failed!';
}
);
}
The constructor prints out the correct values from the json file for rest fqdn and rest port. However, when I execute my getRates call, the fqdn and port are undefined. What do I need to do to get the values propagated to getRates()?
getRates(): Observable<any> {
console.log('RateService - getRates() - getFqdn(): ', this._fileService.getFqdn()); // prints undefined
return this._http.get(this.rateUrl)
.do(data => {
console.log('RateService: getRates(): ' + JSON.stringify(data))
})
.catch(this.handleError);
}
Many thanks!