How to read a .json file in the module.config () of the Angular?

1

I have a config.json file in the root of my project with some information that can be changed: folder path, etc.

I can not create constants (angular.constant) in the code, as I said the values of the file can be changed in production.

But I need to read this file in module.config () and I'm not getting it, how can I do that?

I need something similar to what I do on Server (Node.js)

var options = JSON.parse(fs.readFileSync(require('path').dirname(require.main.filename) + '/config.json'));

Configuration file:

{
  "port": "3000",
  "ipserver": "127.0.0.1",
  "portserver": "3007"
}
    
asked by anonymous 28.11.2016 / 12:32

3 answers

2

You should put this .json file inside a folder in public and access it using $http :

$http.get("./conf/configuracao.json").success(function(dados, status, headers, config) {
  ...
}).error(function(dados, status, headers, config) {
  ...
});

You can inject dependency with a solution that is not optimal but works in most cases in .config :

var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
    
28.11.2016 / 12:41
1

Javascript does not have direct access to the disk, this means that there is no function that directly accesses a file, such as fs.readFile of node.js or Java File reader. I suggest two options:

HTTP GET

$http.get('/caminho/config.json').then((res)=>{
     var configuracao = res.data;
});

This way you can load the file and read the properties. Then with the result apply as desired.

USE ANY AUTOMATIZER

Like Grunt or Gulp for example

    
28.11.2016 / 12:41
1

As you yourself commented in another answer, you can not use $http within config. I suggest you use an ajax request with pure javascript.

angular.config(config);

config.inject = [...]; // injeção dos seus provider

function config(...) {
  var configAjax = new XMLHttpRequest();
  configAjax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var json = JSON.parse(configAjax.responseText);
      ... resto de sua configuração
    }
  }

  configAjax.open('GET', 'path/do/json', true);
  configAjax.send();
}
    
28.11.2016 / 12:55