AngularJS读取web.config值

时间:2014-08-07 15:16:09

标签: angularjs rest web-config

我有一个angularjs工厂服务,它调用REST服务。我的问题是目前REST网址是在工厂服务中硬编码的。我想删除这个硬编码

(function () {
'use strict';

var auctionServices = angular.module('auctionService', ['ngResource']);


//TODO: USE BASE URL SO THAT CAN POINT TO LOCALHOST OR ACTUAL WEB SERVER
var baseUrl = "http://localhost:5037";

auctionServices.factory('auctions', ['$resource', function ($resource) {

    return $resource(baseUrl + '/services/rest/auctions', {}, {
        filter: {
            url: baseUrl + '/services/rest/auctions?location=:location&status=:status',
            isArray: true,
            params: { location: '@location', status: '@status' },
            withCredentials: true,
            cache: false
        },

我的问题在于以下行

var baseUrl = "http://localhost:5037";

我需要从web.config设置baseUrl值,或者请帮助我使用其他更好的方法。

3 个答案:

答案 0 :(得分:2)

如果你的问题是将所有全局配置移到一个文件中,你可以使用常量:创建一个这样的config.js文件:

angular.module('myApp').constant('configs', {
  baseUrl: 'http://localhost:5037'
})

然后在你的工厂注入配置:

auctionServices.factory('auctions', ['$resource', 'configs', function ($resource, configs){
}

configs.baseUrl包含您的网址

答案 1 :(得分:1)

如果您的应用是"http://localhost:5037"提供的,那么您可以

$resource('/services/rest/auctions')

$resource('/user/:userId/card/:cardId')

除非您提供跨域服务,否则您的应用和REST API路径会有所不同。

在这种情况下,您可以将baseUrl设为

module.value('APP_CONTEXT',{}).
module.run(function($location, APP_CONTEXT)) {
  var baseUrlConstuct = null;
 //your logic here to get the domain name from 
 //$location.path() and construct a base url.

  APP_CONTEXT.baseUrl = baseUrlConstuct;

} 

然后在你的工厂

auctionServices.factory('auctions', 
        ['$resource', 'APP_CONTEXT', function ($resource, APP_CONTEXT) {

     return $resource(APP_CONTEXT.baseUrl + '/services/rest/auctions', {}, {
     }
}

我可能会建议使用Restangular - 所有这一切都非常巧妙,包括其他gooodies。

答案 2 :(得分:1)

我们在config.js文件中配置它,以及我们这样做

//custom config settings
var appServicesHostName = "http\\://localhost\\:62784/api";
var memberServicesHostName = "http\\://localhost\\:48089";
var coverageServiceHostName = "http\\://localhost\\:5841";


var config = {
    appServicesHostName: appServicesHostName,
    memberServicesHostName: memberServicesHostName,
    coverageServiceHostName: coverageServiceHostName,
};

app.value("config", config);

然后你可以将它注入你的服务,就像这样

angular.module('app').factory(serviceId,
        ['$q', '$http', 'config', 'Dependents', inRelatedInsuredEditDataSvc]);

这回答了你的问题,但你仍然在硬编码网址的一部分。更好的方法是配置您的路线并命名它们。他们可以移动您的路线,更改它们而无需在整个地方进行更改。例如,在config.route.js

(function () {

    'use strict';

    var app = angular.module('app');

    // Collect the routes
    app.constant('routes', getRoutes());

    // Configure the routes and route resolvers
    app.config(['$routeProvider', 'routes', routeConfigurator]);

    function routeConfigurator($routeProvider, routes) {

        routes.forEach(function (r) {
            $routeProvider.when(r.url, r.config);
        });

        $routeProvider.otherwise({ redirectTo: '/insureds/search' });
    }

    // Define the routes 
    function getRoutes() {
        return [
            {
                name: 'InsuredsSearchView',
                url: '/insureds/search',
                config: {
                    templateUrl: 'app/insured/search/inSearch.html',
                    reloadOnSearch: false,
                    settings: {}
                }
            },
            {
                name: "InsuredCallLogAdd",
                url: '/insureds/:insuredId/callLogs/add',
                config: {
                    templateUrl: 'app/insured/callLog/edit/inCallLogEdit.html',
                    reloadOnSearch: false,
                    settings: {}
                }
            }
    }

})();

正如您所看到的,我们为每条路线命名并按名称引用它,而不是在整个地方硬编码网址。您现在需要的只是提供路线的服务,例如

(function () {
    'use strict';

    var serviceId = 'routesSvc';

    angular.module('app').factory(serviceId, ['$location', 'routes', routesSvc]);

    function routesSvc($location, routes) {
        // Define the functions and properties to reveal.
        var service = {
            getPath: getPath,
            navigateTo: navigateTo,
            getTemplateUrl: getTemplateUrl
        };

        return service;

        function getPath(routeName, routeParameters) {

            var route = _.findWhere(routes, { name: routeName });

            if (route == undefined) {
                //EP: finish - use $log and throw error
                console.log("route: " + routeName + " does not exist");
             }

            var qParameterKeys = [];

            var path = route.url;

            for (var key in routeParameters) {
                if (path.indexOf(":" + key) == -1) {
                    qParameterKeys.push(key);
                } else {
                    path = path.replace(":" + key, routeParameters[key]);
                }
            }

            if (qParameterKeys.length > 0) {
                path = path + "?";

                key = qParameterKeys[0];
                var item = routeParameters[key];
                var value = angular.isObject(item) ? angular.toJson(item) : item;

                path = path + key + "=" + value;

                for (var i = 1; i < qParameterKeys.length; i++) {
                    key = qParameterKeys[i];
                     item = routeParameters[key];
                     value = angular.isObject(item) ? angular.toJson(item) : item;
                     path = path + '&' + key + "=" + value;
                }

            }
            return path;
        }

        function navigateTo(routeName, routeParameters) {
            $location.url(getPath(routeName, routeParameters));
        }

        function getTemplateUrl(routeName) {
            var route = _.findWhere(routes, { name: routeName });

            if (route == null) throw (routeName + " is not defined in config.route.js");

            return route.config.templateUrl;

        }
    }
})();

然后你可以像这样使用它

<a data-ng-href="#{{getPath('BatchDefaultView',{batchId:result.batchId})}}">

请参阅,没有硬编码的网址

如果您需要有关路线或模板的其他信息,您甚至可以通过范围使其可用,例如

(function () {
    'use strict';

    var app = angular.module('app');

    app.run(function ($rootScope, routesSvc) {

        $rootScope.getPath = function (routeName, parameters) {
            return routesSvc.getPath(routeName, parameters);
        };

        $rootScope.navigateTo = function(routeName, parameters) {
            routesSvc.navigateTo(routeName, parameters);
        };

        $rootScope.getTemplateUrl = function(routeName) {
           return routesSvc.getTemplateUrl(routeName);
        };
    });
})();

希望这可以帮助您保持清洁。