I need to import a Json file from the assets folder containing URLs like the following:
config.json:
{
"url1": "https://jsonplaceholder.typicode.com/posts",
"url2" : "https://reqres.in/api/users",
"url3":"https://fakerestapi.azurewebsites.net/api/Authors"
}
Instead of hardcoding the URLs, I want to import them from the Json file. However, I am unsure about how to do this precisely.
Any advice or scenarios would be greatly appreciated. The issues I am facing are as follows:
1. How can I import the Json file into environment.ts
so that a service can consume the API?
2. If I import the file, it needs to be the same for both production and local development environments (dev
).
What I desire :
I have a configuration file with URL's stored in a .json
file within the assets folder. Instead of loading environments.prod
or .ts
, I want to load my Json file config and run my application based on that.
What I have done:
Below is the content of my Json file placed in the asset folder:
{
"baseUrl": "https://jsonplaceholder.typicode.com/",
"baseUrl2": "https://reqres.in/api/users"
}
ConfigServiceService.ts for storing the configuration file:
public _config: Object;
constructor(public http:Http) { }
getData(){
debugger;
return this.http.get("./assets/config.json").pipe(map(res => res.json()));
}
Following this, I created a ServiceProviderService.ts for calling 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;
});
}
app.component.ts
title = 'sample';
constructor(public serv :ServiceProviderService){
this.serv.jsonData();
}
I am having trouble retrieving the Json data. If I put the logic inside the constructor in ServiceProviderService.ts, then I get undefined.
Note: If there are multiple URLs, each URL should be distributed to separate service files. For example, one base URL for one service file and another base URL for another file. How can I achieve this?
https://stackblitz.com/edit/read-local-json-file-5zashx
In app.component.ts, I am encountering issues with getting undefined data.