I want to import a Json file which is in assets folder where I have below urls:
config.json:
{
"url1": "https://jsonplaceholder.typicode.com/posts",
"url2" : "https://reqres.in/api/users",
"url3":"https://fakerestapi.azurewebsites.net/api/Authors"
}
So instead of hard coding the URL, I want to import from Json file, but I am not sure how to do that exactly.
Any suggestions or scenarios would be appreciated, below are my issues:
1. How to import Json file to environment.ts
and from there I will have a service which consumes the api
2. If I import the file, it needs to be the same for prod and loc dev
also
what I want :
I have a config file where it contains some URL's in .json
file stored in asset folder now instead of loading environments.prod
or .ts
, I want to load my Json file config and basing on that I want to run my application
what I did:
Below is my Json file which I placed in asset folder
{
"baseUrl": "https://jsonplaceholder.typicode.com/",
"baseUrl2": "https://reqres.in/api/users"
}
ConfigServiceService.ts for storing config file
public _config: Object;
constructor(public http:Http) { }
getData(){
debugger;
return this.http.get("./assets/config.json").pipe(map(res => res.json()));
}
After this, I create 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 not able to get the Json data and if I am putting the logic which is there is ngOnInit in ServiceProviderService.ts file if I put it in constructor then I am getting undefined.
Note : here if there are more than once url then each url is distributed to various seperate service file suppose base1 url for 1 service file ans base2 url for another file how can I achieve that
https://stackblitz.com/edit/read-local-json-file-5zashx
in app.component.ts im getting undefined