【问题标题】:Best way to save and use config settings in AngularJS在 AngularJS 中保存和使用配置设置的最佳方式
【发布时间】:2014-08-08 01:42:45
【问题描述】:

我是 AngularJS 的新手,只是构建一个应用程序来学习它。我的应用程序调用 REST API,现在我在应用程序中硬编码了主机名。我想在应用程序设置中进行此设置(也许以后有地方可以配置它)。我以为我会从一个常数开始。它应该像这样进入我的 app.js 吗?如果是这样,我不确定将其添加到带有 $routeProvider 的 .config 设置的语法

 (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's get sent back to main route
                .otherwise({ redirectTo: "/main" });
        }); // End App Config

    }());

这是需要使用它的模块(从控制器调用):

(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");

}());

有人可以启发他们设置和获取它的最佳方式吗?

谢谢

【问题讨论】:

    标签: angularjs constants


    【解决方案1】:

    我目前通过使用模板在后端构建根.html 文件来做到这一点。例如,在 node.js 中使用 doT 模板,我把它放在我的其他 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
    }]);
    

    【讨论】:

      【解决方案2】:

      进行配置的最佳位置是在 Provider 和您的配置块内。

      提供者公开了一个 API,允许您在将服务注入控制器和指令之前对其进行配置。

      假设您有一个名为 myService 的服务,您希望将它注入到您的控制器函数中,如下所示:

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

      而 myService 负责通过 Web 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();
        });
      

      【讨论】:

      • 感谢详细的回复。我试图应用它,但我仍然完全失去了去哪里。您说“您可以像这样定义 myServiceProvider”的地方是一个新文件(将内容分开)。什么是 */Injectables*/.什么是“使用 webapiurl”
      • 我建议您将所有内容放在同一个脚本文件中,直到您掌握了窍门。 Angular 使用依赖注入将服务注入到你的控制器函数(以及指令)中。 Angular 的很多地方都使用了依赖注入。你应该搜索“依赖注入在 Angular 中是如何工作的”,你会发现一些很好的教程。
      • 在您的提供程序中,一旦您配置了 'webapiurl' 变量,您就可以按照您想要的方式使用它。这只是一个示例,用于演示目的。你可以使用任何你想要的自定义变量。
      【解决方案3】:

      我无法获得提供的答案来工作(没有理由认为他们不会)。这就是我所做的。

      我的主要 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's 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 的知识,所以我继续使用它。

      问候

      标记

      【讨论】:

        【解决方案4】:

        我使用了另一个模块,并像这样将它注入到应用程序模块中

        1. 创建 constant.js 并将其包含在您的 index.html 中并在其中添加以下代码

          angular.module(<strong>'constantsModule'</strong>, []).constant(<strong>'BASEURL'</strong>, '@987654321@');

        2. 在 app.js 中,注入 'constantsModule' 以便其中的所有常量都可用于 'haClient'

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

        3. 在landingCtrl内部,由于它在'haClient'的范围内,我们可以从'constantsModule'注入BASEURL常量

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

        【讨论】:

          猜你喜欢
          • 2015-10-15
          • 1970-01-01
          • 2013-03-28
          • 2016-12-23
          • 2022-12-21
          • 1970-01-01
          • 2011-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多