4

在使用 AngularJS 的 $http 服务时,我发现很难管理所有到后端的 url - 它们分布在控制器的代码中。有时它们甚至是重复的。大多数情况下,它们都是$http.get('/api/something').then(...).

将它们全部放到不同的服务中听起来很不合理:它只是一行代码,可能只是很小的修改(比如添加标题等)。

其他解决方案可能是将它们放入常量中,但在这种情况下,我仍然会使用$http.get(APIURLs.SomeURL)看起来有点冗长的...

所以问题是:管理后端 URL 的最佳方法是什么?

4

3 回答 3

2

目前我想出了将它们分组为服务并将它们公开为对 $http 的调用的想法。这是我的解决方案: http ://plnkr.co/edit/VjqXHBV54bmjKCuGJ4qX?p=preview

服务:

.factory('AdminAPI', function($http) {
   var apiMap = {
     'DeleteAuth': {url:'/api/oauth/delete',method:'PUT'},
     'GetInvalidUser': {url:'/api/users/invalid',method:'GET'},
     'CreateItem': {url:'/api/items/create',method:'POST'}     
   };
   var api = {};  
   var prepareCall = function(config) {
     return function(params) {  
       var requestConfig = angular.copy(config);
       if (config.method=='GET')
          requestConfig.params = params;
       else 
          requestConfig.data = params;       
       return $http(requestConfig);
     };
   };
   for(var name in apiMap) 
     api[name] = prepareCall(apiMap[name]);   
   return api;
});

在控制器中,我执行以下操作:

AdminAPI.DeleteAuth({data:123}).then(function(result) {
  //
});

在这种情况下,我有一些抽象(不必注入$http控制器),因此单元测试变得更容易一些(我不必使用 $httpBackend 服务,只需模拟我的服务调用)。

于 2013-03-25T13:42:46.103 回答
0

利用角度Module.constant

  • 将可重复使用的设置移动到单个对象;
  • 定义包装此对象的角度模块:

    angular.module('myApp.constants', []).constant('config', {
        ROUTES: {
           home: '/home.html',
           about: '/about.html'
        }
    });
    
  • myApp.constants将模块与所有其他模块一起加载到应用程序中:

    angular.module('myApp', [
        'myApp.constants',
        'myApp.services',
        'myApp.controllers',
        'myApp.filters',
        'myApp.directives'
    ]);
    

之后,您可以注入config依赖项并访问定义的哈希。

于 2013-03-25T13:55:23.327 回答
0

好问题。我建议的方法是将常量放在这样的constant声明中:

angular.module('fooApp').constant('config', {
                                      api: {
                                        baseUrl: 'http://api.example.com/api',
                                        key: 'SECRET_API_KEY',
                                      }
});

你可以实现一个httpResourceFactory负责创建 $http 或 $resource 引用,这些引用使用 config.xml 中定义的常量指向不同的端点。这可以在服务中实现。

然后可以将所有 API 端点定义放入单个服务中。

angular.module('fooApp').factory('dataService', ['httpResourceFactory',  function(httpResourceFactory) {

    var PUBLIC_API = {};

    PUBLIC_API.Orders = httpResourceFactory('/orders/:id');
    PUBLIC_API.Users = httpResourceFactory('/some-url/users/:id');


    return PUBLIC_API;

  }]);

然后在您的控制器中,您可以注入dataService并执行以下操作:

$scope.users = dataService.Users.query();

希望这能澄清它。我很着急,所以问得更具体一些,稍后我会提供更多示例。

于 2013-03-25T22:35:45.250 回答