how to import .json config to environment.ts and consume api using angular The Next CEO of Stack OverflowAngular: Is it possible to read a json file after buildinghow to consume multiple urls using injection token/App_init concept using angularHow to apply !important using .css()?How can I pretty-print JSON using JavaScript?How to parse JSON using Node.js?TypeScript - I can't call my json with http get using Angular 2changing angular config based on azure deployment slotHow to use config data in nested forRoot modulesprovide google maps api key from config.json fileHow to avoid using json-server with AngularAngular Google Maps (AGM): getting the Api Key in the app.moduleunable to retrieve json data from assets folder using angular

What can we do to stop prior company from asking us questions?

Term for the "extreme-extension" version of a straw man fallacy?

What does "Its cash flow is deeply negative" mean?

Which organization defines CJK Unified Ideographs?

Why is there a PLL in CPU?

Need some help with wall behind rangetop

Grabbing quick drinks

Too much space between section and text in a twocolumn document

Implement the Thanos sorting algorithm

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

How do spells that require an ability check vs. the caster's spell save DC work?

Return the Closest Prime Number

Rotate a column

Horror movie/show or scene where a horse creature opens its mouth really wide and devours a man in a stables

How to start emacs in "nothing" mode (`fundamental-mode`)

How should I support this large drywall patch?

What is the purpose of the Evocation wizard's Potent Cantrip feature?

Why do remote companies require working in the US?

Can the Reverse Gravity spell affect the Meteor Swarm spell?

Is HostGator storing my password in plaintext?

Go Pregnant or Go Home

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

How to get regions to plot as graphics

Trouble understanding the speech of overseas colleagues



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



The Next CEO of Stack OverflowAngular: Is it possible to read a json file after buildinghow to consume multiple urls using injection token/App_init concept using angularHow to apply !important using .css()?How can I pretty-print JSON using JavaScript?How to parse JSON using Node.js?TypeScript - I can't call my json with http get using Angular 2changing angular config based on azure deployment slotHow to use config data in nested forRoot modulesprovide google maps api key from config.json fileHow to avoid using json-server with AngularAngular Google Maps (AGM): getting the Api Key in the app.moduleunable to retrieve json data from assets folder using angular










-1















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 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 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



enter image description here










share|improve this question

















This question has an open bounty worth +50
reputation from Dexter ending ending at 2019-03-30 16:44:45Z">tomorrow.


Looking for an answer drawing from credible and/or official sources.











  • 1





    You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

    – penleychan
    Mar 21 at 16:46











  • @penleychan by environment.ts cant i do that ?

    – Dexter
    Mar 21 at 16:55











  • No, environment.ts is static

    – penleychan
    Mar 21 at 17:00











  • Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

    – Doug S.
    Mar 25 at 14:49











  • @DougS. BUILD would be better

    – Dexter
    Mar 25 at 16:52
















-1















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 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 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



enter image description here










share|improve this question

















This question has an open bounty worth +50
reputation from Dexter ending ending at 2019-03-30 16:44:45Z">tomorrow.


Looking for an answer drawing from credible and/or official sources.











  • 1





    You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

    – penleychan
    Mar 21 at 16:46











  • @penleychan by environment.ts cant i do that ?

    – Dexter
    Mar 21 at 16:55











  • No, environment.ts is static

    – penleychan
    Mar 21 at 17:00











  • Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

    – Doug S.
    Mar 25 at 14:49











  • @DougS. BUILD would be better

    – Dexter
    Mar 25 at 16:52














-1












-1








-1








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 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 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



enter image description here










share|improve this question
















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 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 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



enter image description here







javascript angular typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 hour ago









Vega

13.9k113961




13.9k113961










asked Mar 21 at 16:41









DexterDexter

4811




4811






This question has an open bounty worth +50
reputation from Dexter ending ending at 2019-03-30 16:44:45Z">tomorrow.


Looking for an answer drawing from credible and/or official sources.








This question has an open bounty worth +50
reputation from Dexter ending ending at 2019-03-30 16:44:45Z">tomorrow.


Looking for an answer drawing from credible and/or official sources.









  • 1





    You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

    – penleychan
    Mar 21 at 16:46











  • @penleychan by environment.ts cant i do that ?

    – Dexter
    Mar 21 at 16:55











  • No, environment.ts is static

    – penleychan
    Mar 21 at 17:00











  • Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

    – Doug S.
    Mar 25 at 14:49











  • @DougS. BUILD would be better

    – Dexter
    Mar 25 at 16:52













  • 1





    You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

    – penleychan
    Mar 21 at 16:46











  • @penleychan by environment.ts cant i do that ?

    – Dexter
    Mar 21 at 16:55











  • No, environment.ts is static

    – penleychan
    Mar 21 at 17:00











  • Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

    – Doug S.
    Mar 25 at 14:49











  • @DougS. BUILD would be better

    – Dexter
    Mar 25 at 16:52








1




1





You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

– penleychan
Mar 21 at 16:46





You would have to create a service that reads the JSON file and inject that to APP_INITIALIZER

– penleychan
Mar 21 at 16:46













@penleychan by environment.ts cant i do that ?

– Dexter
Mar 21 at 16:55





@penleychan by environment.ts cant i do that ?

– Dexter
Mar 21 at 16:55













No, environment.ts is static

– penleychan
Mar 21 at 17:00





No, environment.ts is static

– penleychan
Mar 21 at 17:00













Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

– Doug S.
Mar 25 at 14:49





Would it be possible to do this during BUILD, or does it have to be during RUNTIME?

– Doug S.
Mar 25 at 14:49













@DougS. BUILD would be better

– Dexter
Mar 25 at 16:52






@DougS. BUILD would be better

– Dexter
Mar 25 at 16:52













5 Answers
5






active

oldest

votes


















2














Because you have static strings in a JSON, which is already in /assets, it's not on the server, you don't need http.get, just import the file wherever you need, even in environment.ts.



JSON:



export const URLS = Object(

"url1": "https://jsonplaceholder.typicode.com/posts",

"url2" : "https://reqres.in/api/users",

"url3":"https://fakerestapi.azurewebsites.net/api/Authors"
)


Then anywhere:



import URLS from 'assets/config.ts';

....

this.url1 = URLS.url1;


//or



let url1 = URL.url1;


Now this.url1 can be used in any api call inside http.get, for example:



 this.http.get(`$this.url1`, headers: this.getHeaders(token) );


or



 this.http.get(`$url1`, headers: this.getHeaders(token) ) // where url1 could be a variable or method parameter, etc...


That's it






share|improve this answer

























  • This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

    – George C.
    12 hours ago











  • @GeorgeC.That is one nice and kind comment!!! Thank you :)

    – Vega
    11 hours ago


















0














You can create constants for all these urls in environment file. I do not see a scenario in your case to put it in a separate json file. For prod, you can use the same environment file by changing default configurations property in angular.json






share|improve this answer






























    0














    You can create a service to read Json file using HttpClient



    export class SettingService 

    constructor(private http: HttpClient)



    public getJSON(file): Observable<any>
    return this.http.get("./assets/configs/" + file + ".json");

    public getSetting()
    // use setting here




    You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page



    Refer Angular: Is it possible to read a json file after building






    share|improve this answer

























    • if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

      – Dexter
      Mar 21 at 16:53











    • yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

      – Hien Nguyen
      Mar 21 at 16:56











    • ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

      – Dexter
      Mar 21 at 16:59











    • so even thought it is prod or dev environment the url wont change right i mean it work right

      – Dexter
      Mar 21 at 17:01












    • you can configure it to prod url version, my project do like this.

      – Hien Nguyen
      Mar 21 at 17:05


















    0














     import environment from '../../../environments/environment';

    domain :string = environment.domain;

    if(!!environment)
    if(environment.qa)
    "url1": "https://jsonplaceholder.typicode.com/posts",

    if(environment.dev)
    "url2" : "https://reqres.in/api/users",




    you can import the baseUrl property in the asset folder to your service file and execute as I mentioned above.



    https://alligator.io/angular/environment-variables/



    Please find the url for detailed explanation of environment variables in angular






    share|improve this answer























    • im trying to get environments from JSON file not static hardcoded urls

      – Dexter
      2 days ago


















    0














    So, I would create a node script called populatedDynamicUrls.js that can read those values IN from the json file, and write those values OUT to the corresponding environment.ts file for that specific environment. THEN your angular build command would look like this: node populateDynamicUrls.js && ng run build, and your angular serve command would look like this: node populateDynamicUrls.js && ng run serve






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285323%2fhow-to-import-json-config-to-environment-ts-and-consume-api-using-angular%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Because you have static strings in a JSON, which is already in /assets, it's not on the server, you don't need http.get, just import the file wherever you need, even in environment.ts.



      JSON:



      export const URLS = Object(

      "url1": "https://jsonplaceholder.typicode.com/posts",

      "url2" : "https://reqres.in/api/users",

      "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
      )


      Then anywhere:



      import URLS from 'assets/config.ts';

      ....

      this.url1 = URLS.url1;


      //or



      let url1 = URL.url1;


      Now this.url1 can be used in any api call inside http.get, for example:



       this.http.get(`$this.url1`, headers: this.getHeaders(token) );


      or



       this.http.get(`$url1`, headers: this.getHeaders(token) ) // where url1 could be a variable or method parameter, etc...


      That's it






      share|improve this answer

























      • This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

        – George C.
        12 hours ago











      • @GeorgeC.That is one nice and kind comment!!! Thank you :)

        – Vega
        11 hours ago















      2














      Because you have static strings in a JSON, which is already in /assets, it's not on the server, you don't need http.get, just import the file wherever you need, even in environment.ts.



      JSON:



      export const URLS = Object(

      "url1": "https://jsonplaceholder.typicode.com/posts",

      "url2" : "https://reqres.in/api/users",

      "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
      )


      Then anywhere:



      import URLS from 'assets/config.ts';

      ....

      this.url1 = URLS.url1;


      //or



      let url1 = URL.url1;


      Now this.url1 can be used in any api call inside http.get, for example:



       this.http.get(`$this.url1`, headers: this.getHeaders(token) );


      or



       this.http.get(`$url1`, headers: this.getHeaders(token) ) // where url1 could be a variable or method parameter, etc...


      That's it






      share|improve this answer

























      • This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

        – George C.
        12 hours ago











      • @GeorgeC.That is one nice and kind comment!!! Thank you :)

        – Vega
        11 hours ago













      2












      2








      2







      Because you have static strings in a JSON, which is already in /assets, it's not on the server, you don't need http.get, just import the file wherever you need, even in environment.ts.



      JSON:



      export const URLS = Object(

      "url1": "https://jsonplaceholder.typicode.com/posts",

      "url2" : "https://reqres.in/api/users",

      "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
      )


      Then anywhere:



      import URLS from 'assets/config.ts';

      ....

      this.url1 = URLS.url1;


      //or



      let url1 = URL.url1;


      Now this.url1 can be used in any api call inside http.get, for example:



       this.http.get(`$this.url1`, headers: this.getHeaders(token) );


      or



       this.http.get(`$url1`, headers: this.getHeaders(token) ) // where url1 could be a variable or method parameter, etc...


      That's it






      share|improve this answer















      Because you have static strings in a JSON, which is already in /assets, it's not on the server, you don't need http.get, just import the file wherever you need, even in environment.ts.



      JSON:



      export const URLS = Object(

      "url1": "https://jsonplaceholder.typicode.com/posts",

      "url2" : "https://reqres.in/api/users",

      "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
      )


      Then anywhere:



      import URLS from 'assets/config.ts';

      ....

      this.url1 = URLS.url1;


      //or



      let url1 = URL.url1;


      Now this.url1 can be used in any api call inside http.get, for example:



       this.http.get(`$this.url1`, headers: this.getHeaders(token) );


      or



       this.http.get(`$url1`, headers: this.getHeaders(token) ) // where url1 could be a variable or method parameter, etc...


      That's it







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited yesterday

























      answered yesterday









      VegaVega

      13.9k113961




      13.9k113961












      • This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

        – George C.
        12 hours ago











      • @GeorgeC.That is one nice and kind comment!!! Thank you :)

        – Vega
        11 hours ago

















      • This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

        – George C.
        12 hours ago











      • @GeorgeC.That is one nice and kind comment!!! Thank you :)

        – Vega
        11 hours ago
















      This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

      – George C.
      12 hours ago





      This is the best answer, I have seen a lot of questions on SO and most of the developers are making their lives harder. Good job @Vega KISS principle 💋

      – George C.
      12 hours ago













      @GeorgeC.That is one nice and kind comment!!! Thank you :)

      – Vega
      11 hours ago





      @GeorgeC.That is one nice and kind comment!!! Thank you :)

      – Vega
      11 hours ago













      0














      You can create constants for all these urls in environment file. I do not see a scenario in your case to put it in a separate json file. For prod, you can use the same environment file by changing default configurations property in angular.json






      share|improve this answer



























        0














        You can create constants for all these urls in environment file. I do not see a scenario in your case to put it in a separate json file. For prod, you can use the same environment file by changing default configurations property in angular.json






        share|improve this answer

























          0












          0








          0







          You can create constants for all these urls in environment file. I do not see a scenario in your case to put it in a separate json file. For prod, you can use the same environment file by changing default configurations property in angular.json






          share|improve this answer













          You can create constants for all these urls in environment file. I do not see a scenario in your case to put it in a separate json file. For prod, you can use the same environment file by changing default configurations property in angular.json







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 21 at 16:46









          Idris RampurawalaIdris Rampurawala

          32




          32





















              0














              You can create a service to read Json file using HttpClient



              export class SettingService 

              constructor(private http: HttpClient)



              public getJSON(file): Observable<any>
              return this.http.get("./assets/configs/" + file + ".json");

              public getSetting()
              // use setting here




              You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page



              Refer Angular: Is it possible to read a json file after building






              share|improve this answer

























              • if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

                – Dexter
                Mar 21 at 16:53











              • yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

                – Hien Nguyen
                Mar 21 at 16:56











              • ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

                – Dexter
                Mar 21 at 16:59











              • so even thought it is prod or dev environment the url wont change right i mean it work right

                – Dexter
                Mar 21 at 17:01












              • you can configure it to prod url version, my project do like this.

                – Hien Nguyen
                Mar 21 at 17:05















              0














              You can create a service to read Json file using HttpClient



              export class SettingService 

              constructor(private http: HttpClient)



              public getJSON(file): Observable<any>
              return this.http.get("./assets/configs/" + file + ".json");

              public getSetting()
              // use setting here




              You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page



              Refer Angular: Is it possible to read a json file after building






              share|improve this answer

























              • if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

                – Dexter
                Mar 21 at 16:53











              • yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

                – Hien Nguyen
                Mar 21 at 16:56











              • ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

                – Dexter
                Mar 21 at 16:59











              • so even thought it is prod or dev environment the url wont change right i mean it work right

                – Dexter
                Mar 21 at 17:01












              • you can configure it to prod url version, my project do like this.

                – Hien Nguyen
                Mar 21 at 17:05













              0












              0








              0







              You can create a service to read Json file using HttpClient



              export class SettingService 

              constructor(private http: HttpClient)



              public getJSON(file): Observable<any>
              return this.http.get("./assets/configs/" + file + ".json");

              public getSetting()
              // use setting here




              You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page



              Refer Angular: Is it possible to read a json file after building






              share|improve this answer















              You can create a service to read Json file using HttpClient



              export class SettingService 

              constructor(private http: HttpClient)



              public getJSON(file): Observable<any>
              return this.http.get("./assets/configs/" + file + ".json");

              public getSetting()
              // use setting here




              You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page



              Refer Angular: Is it possible to read a json file after building







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 21 at 16:55

























              answered Mar 21 at 16:50









              Hien NguyenHien Nguyen

              1,4281715




              1,4281715












              • if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

                – Dexter
                Mar 21 at 16:53











              • yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

                – Hien Nguyen
                Mar 21 at 16:56











              • ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

                – Dexter
                Mar 21 at 16:59











              • so even thought it is prod or dev environment the url wont change right i mean it work right

                – Dexter
                Mar 21 at 17:01












              • you can configure it to prod url version, my project do like this.

                – Hien Nguyen
                Mar 21 at 17:05

















              • if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

                – Dexter
                Mar 21 at 16:53











              • yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

                – Hien Nguyen
                Mar 21 at 16:56











              • ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

                – Dexter
                Mar 21 at 16:59











              • so even thought it is prod or dev environment the url wont change right i mean it work right

                – Dexter
                Mar 21 at 17:01












              • you can configure it to prod url version, my project do like this.

                – Hien Nguyen
                Mar 21 at 17:05
















              if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

              – Dexter
              Mar 21 at 16:53





              if we put in environment.ts is ther any issue why im askng bcoz as i have 3 types of urls so i want to use 3 url for 3 diff services from environment

              – Dexter
              Mar 21 at 16:53













              yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

              – Hien Nguyen
              Mar 21 at 16:56





              yes, you can use both 3 diff url, but you should keep url in session storage or localstorage for refreshing page

              – Hien Nguyen
              Mar 21 at 16:56













              ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

              – Dexter
              Mar 21 at 16:59





              ok what u suggested is good so what ur view for best practice in service or environment and saving url in storage is not good thing so ur first approach is better

              – Dexter
              Mar 21 at 16:59













              so even thought it is prod or dev environment the url wont change right i mean it work right

              – Dexter
              Mar 21 at 17:01






              so even thought it is prod or dev environment the url wont change right i mean it work right

              – Dexter
              Mar 21 at 17:01














              you can configure it to prod url version, my project do like this.

              – Hien Nguyen
              Mar 21 at 17:05





              you can configure it to prod url version, my project do like this.

              – Hien Nguyen
              Mar 21 at 17:05











              0














               import environment from '../../../environments/environment';

              domain :string = environment.domain;

              if(!!environment)
              if(environment.qa)
              "url1": "https://jsonplaceholder.typicode.com/posts",

              if(environment.dev)
              "url2" : "https://reqres.in/api/users",




              you can import the baseUrl property in the asset folder to your service file and execute as I mentioned above.



              https://alligator.io/angular/environment-variables/



              Please find the url for detailed explanation of environment variables in angular






              share|improve this answer























              • im trying to get environments from JSON file not static hardcoded urls

                – Dexter
                2 days ago















              0














               import environment from '../../../environments/environment';

              domain :string = environment.domain;

              if(!!environment)
              if(environment.qa)
              "url1": "https://jsonplaceholder.typicode.com/posts",

              if(environment.dev)
              "url2" : "https://reqres.in/api/users",




              you can import the baseUrl property in the asset folder to your service file and execute as I mentioned above.



              https://alligator.io/angular/environment-variables/



              Please find the url for detailed explanation of environment variables in angular






              share|improve this answer























              • im trying to get environments from JSON file not static hardcoded urls

                – Dexter
                2 days ago













              0












              0








              0







               import environment from '../../../environments/environment';

              domain :string = environment.domain;

              if(!!environment)
              if(environment.qa)
              "url1": "https://jsonplaceholder.typicode.com/posts",

              if(environment.dev)
              "url2" : "https://reqres.in/api/users",




              you can import the baseUrl property in the asset folder to your service file and execute as I mentioned above.



              https://alligator.io/angular/environment-variables/



              Please find the url for detailed explanation of environment variables in angular






              share|improve this answer













               import environment from '../../../environments/environment';

              domain :string = environment.domain;

              if(!!environment)
              if(environment.qa)
              "url1": "https://jsonplaceholder.typicode.com/posts",

              if(environment.dev)
              "url2" : "https://reqres.in/api/users",




              you can import the baseUrl property in the asset folder to your service file and execute as I mentioned above.



              https://alligator.io/angular/environment-variables/



              Please find the url for detailed explanation of environment variables in angular







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 2 days ago









              JayKJayK

              3819




              3819












              • im trying to get environments from JSON file not static hardcoded urls

                – Dexter
                2 days ago

















              • im trying to get environments from JSON file not static hardcoded urls

                – Dexter
                2 days ago
















              im trying to get environments from JSON file not static hardcoded urls

              – Dexter
              2 days ago





              im trying to get environments from JSON file not static hardcoded urls

              – Dexter
              2 days ago











              0














              So, I would create a node script called populatedDynamicUrls.js that can read those values IN from the json file, and write those values OUT to the corresponding environment.ts file for that specific environment. THEN your angular build command would look like this: node populateDynamicUrls.js && ng run build, and your angular serve command would look like this: node populateDynamicUrls.js && ng run serve






              share|improve this answer



























                0














                So, I would create a node script called populatedDynamicUrls.js that can read those values IN from the json file, and write those values OUT to the corresponding environment.ts file for that specific environment. THEN your angular build command would look like this: node populateDynamicUrls.js && ng run build, and your angular serve command would look like this: node populateDynamicUrls.js && ng run serve






                share|improve this answer

























                  0












                  0








                  0







                  So, I would create a node script called populatedDynamicUrls.js that can read those values IN from the json file, and write those values OUT to the corresponding environment.ts file for that specific environment. THEN your angular build command would look like this: node populateDynamicUrls.js && ng run build, and your angular serve command would look like this: node populateDynamicUrls.js && ng run serve






                  share|improve this answer













                  So, I would create a node script called populatedDynamicUrls.js that can read those values IN from the json file, and write those values OUT to the corresponding environment.ts file for that specific environment. THEN your angular build command would look like this: node populateDynamicUrls.js && ng run build, and your angular serve command would look like this: node populateDynamicUrls.js && ng run serve







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 2 days ago









                  Doug S.Doug S.

                  3871824




                  3871824



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285323%2fhow-to-import-json-config-to-environment-ts-and-consume-api-using-angular%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현