Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using config files with angularjs

I'm creating a angular app that talks to a node backend express application and using a config file to set env variables in my node app I can access my config file like this:

index.js

  var port = config.get("server:port");
  var server = app.listen(port, function() {});

My config file looks like this:

app.config.js

    module.exports =
    {
"server":{
    "host":"localhost",
    "port":3000
  },
      "mongodb": "",

      "redis": {
        "loadBalancerInstance": {
          "host": "server",
          "port": {
            "default": "6379"
          }
        }
      },
      "elastic": {
        "server": "server",
        "port": "9200",
        "user":"foo",
        "password":"bar"
      },
      "log": {
        "level": "info",
        "filename": "",
        "console": true,
        "logio": {
          "port": "28777",
          "node_name": "this-server-name",
          "host": "server"
        }
      }
    };

I have statically defined the route/port to a backend

datafactory.js

angular.module('dashboard.factories')
  .factory('DataFactory', function($http, $q, FormatFactory) {
    var backend = function(apiEndPoint, clientKey) {
      clientKey = clientKey || "";
      var deferred = $q.defer();
      $http.get("http://localhost:3000/<-(pull this from config file)" + apiEndPoint + "/" + clientKey)

My question is how can I access app.config.js within angular and dynamically set host/port within my angular service

like image 718
user1952312 Avatar asked Mar 06 '26 03:03

user1952312


1 Answers

I suppose if you're stuck on using the same configuration file that your node server uses, you'll have to make the .js file available to a GET request from your app, which you'll then have to parse out the string into JSON.

Edit: You're going to have to have two configuration files, one available to your node server, and one for your angular app. Now, if you want the source to be one file, you could build that into your build process - if you use something like gulp or grunt, this would be reasonably easy. It could take the singular config file and build two files - the node server config file, and an angular module (I would suggest a constant or value) that you could inject into your data services.

like image 165
Neil S Avatar answered Mar 07 '26 16:03

Neil S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!