What I Desire:: In my project, I have a configuration file that contains URLs in a .json format. This file is stored in the asset folder. Instead of loading environments.prod or .ts files, I want to load this json configuration file and utilize it to run my application.
My Approach:
Here is the content of my json file located in the asset folder:
{
"baseUrl": "https://jsonplaceholder.typicode.com/",
"baseUrl2": "https://reqres.in/api/users"
}
I then created a ConfigServiceService.ts to handle this configuration file.
public _config: Object;
constructor(public http:Http) { }
getData(){
debugger;
return this.http.get("./assets/config.json").pipe(map(res => res.json()));
}
After setting up the config service, I created a ServiceProviderService.ts to make use of the service file.
configData:any;
constructor(public http:Http,public config:ConfigServiceService) {
}
jsonData(){
debugger;
return this.configData;
}
ngOnInit(){
debugger;
this.config.getData().subscribe(res =>{
console.log(res);
this.configData = res;
});
}
Next, I implemented the logic in the app.component.ts
.
title = 'sample';
constructor(public serv :ServiceProviderService){
this.serv.jsonData();
}
However, I am facing an issue where I am unable to retrieve the json data. If I move the logic from ngOnInit in ServiceProviderService.ts file to the constructor, I receive 'undefined'.
Note: If there are multiple URLs in the configuration file, each URL needs to be assigned to a separate service file. How can I accomplish this?