Saturday, 23 March 2019

how to import .json config to environment.ts and consume api using angular

here i want to import a json file which is there in assets folder where i will 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 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 same for prod and loc dev also

what i want : i have a config file where it contains some urls 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 run my application

what i did

 below is my json file    which i placed  asset folder



  {
        "baseUrl": "https://jsonplaceholder.typicode.com/",
        "baseUrl2": "https://reqres.in/api/users"
    }

now i created a ConfigServiceService.ts fpr 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;
        });


      }

now i am calling the app.component.ts

   title = 'sample';
      constructor(public serv :ServiceProviderService){
        this.serv.jsonData();
      }

now my issue is 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 put it in constructor then i am getting undefined

note : here if there are more that 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



from how to import .json config to environment.ts and consume api using angular

No comments:

Post a Comment