Best way to save and use configuration settings in AngularJS

I am new to AngularJS and just building an application to learn it. My application calls the REST API, and now I have a host name hardcoded in the application. I want to do this in the settings of the application (and maybe later to configure it somewhere later). I thought I would start with a constant. Should it go in my app.js like this? If so, I'm not sure of the syntax for adding it to the .config settings with $ routeProvider there too

 (function () {

        // Define module and add dependencies inside []
        var app = angular.module("haClient", ["ngRoute"]);

        app.constant('hostname', 'http://192.192.192.192:8176');

        app.config(function ($routeProvider) {
            $routeProvider
                // Register routes
                // Main route
                .when("/main", {
                    templateUrl: "main.html",
                    controller: "MainController"//,
                    //activeTab: 'home'
                })
                // Device List 
                .when("/devices", {
                    templateUrl: "devicelist.html",
                    controller: "DeviceListController"
                })
                // Device details (param is device name)
                .when("/device/:devicename", {
                    templateUrl: "device.html",
                    controller: "DeviceController"
                })
                // Invalid URL get sent back to main route
                .otherwise({ redirectTo: "/main" });
        }); // End App Config

    }());

This is the module that should use it (called from controllers):

(function () {

    var deviceCtrl = function ($http) {
        var getDevices = function () {
            return $http.get("http://192.192.192.192:8176/devices.json/")
                          .then(function (response) {
                              return response.data;
                          });
        };

        // get details and return a promise
        var getDeviceDetails = function (deviceName) {
            return $http.get("http://192.192.192.192:8176/devices/" + deviceName + ".json/")
                          .then(function (response) {
                              return response.data;
                          });
        };


        // Public API
        return {
            getDeviceDetails: getDeviceDetails,
            getDevices: getDevices
    };
    };

    var module = angular.module("haClient");

}());

Can someone enlighten them in the best way to establish it and receive it?

thank

+4
source share
4

, root .html . , doT node.js, js:

<!-- load any templated constants -->
<script>
    angular.module('mymod').constant('globals', {
        api: '{{=it.api}}'
    });
</script>

, , . , :

angular.module('somemod', []).factory('myservice', ['globals', function(globals){
    // use globals.api or what ever you set here for example
}]);
0

- .

API, , .

, myService, :

 app.controller('ctrl', function($scope, myService) { ...});

myService -API. , URL- htt://servername/, .

myServiceProvider :

 app.provider('myService', function(){
        var webapiurl;
        this.setWebServiceUrl = function (url) {
                webapiurl = url;
        }

        // the injector will call the $get function to create the singleton service that will be injected
        this.$get = function( /*injectables*/) {
             return {
                      getData: function() {... Use webapiurl ...}
              }
        }
   });

:

  app.config(function(myServiceProvider){
          myServiceProvider.setWebServiceUrl('htt://servername');

  });

, , :

 app.controller('ctrl', function($scope, myService) {
         $scope.data = myService.getData();
  });
0

( , ). .

app.js()

(function () {

    // Define module and add dependencies inside []
    var app = angular.module("haClient", ["ngRoute"]);

    //constants
    app.constant('mySettings', {
        baseURL:      'http://192.192.192.192:8176',
        otherSetting: 'XYZ'
    });


    app.config(function ($routeProvider) {
        $routeProvider
            // Register routes
            // Main route
            .when("/main", {
                templateUrl: "main.html",
                controller: "MainController"//,
                //activeTab: 'home'
            })
            // Device List 
            .when("/devices", {
                templateUrl: "devicelist.html",
                controller: "DeviceListController"
            })
            // Device details (param is device name)
            .when("/device/:devicename", {
                templateUrl: "device.html",
                controller: "DeviceController"
            })
            // Invalid URL get sent back to main route
            .otherwise({ redirectTo: "/main" });

    }); // End App Config

}());

( mySettings , mySettings.baseURL):

(function () {

     var deviceCtrl = function ($http, $log, mySettings) {

         $log.info("DeviceCtrl - baseURL: " + mySettings.baseURL);

         // get device list and return a promise
         var getDevices = function () {
            return $http.get(mySettings.baseURL + "/devices.json")
                          .then(function (response) {
                              return response.data;
                          });
        };

        // get details and return a promise
        var getDeviceDetails = function (deviceName) {
            $log.info("DeviceCtrl - Getting device info for " + deviceName);
            return $http.get(mySettings.baseURL + "/devices/" + deviceName + ".json")
                          .then(function (response) {
                              return response.data;
                          });
        };


        // Public API
        return {
            getDeviceDetails: getDeviceDetails,
            getDevices: getDevices
    };
    };

     var module = angular.module("haClient");
     module.factory("deviceCtrl", deviceCtrl);

}());

, , ( , ), (), - . Angular, .

0
source

I used a different module and injected it into an application module like this

  • Create a .js constant and include it in your index.html and add the following code inside this

    angular.module('constantsModule', []).constant('BASEURL', 'http://google.com');

  • Inside app.js, enter "constantsModule" so that all the constants inside it are accessible to "haClient"

    angular.module('haClient', [ 'constantsModule' ]) .config(function ($routeProvider) { .when('/', { templateUrl: 'views/landing.html', controller: 'landingCtrl' }) });

  • Inside landingCtrl, since it is in the 'haClient' area, we can enter the BASEURL constant from the 'constantsModule'

    angular.module('haClient').controller('landingCtrl', function ($scope, BASEURL) { // just to show, how to access it inside controller $scope.baseurl = BASEURL; });

0
source

Source: https://habr.com/ru/post/1544995/


All Articles