【问题标题】:What is the best approach for integrating AngularJS with a non-RESTful API?将 AngularJS 与非 RE​​STful API 集成的最佳方法是什么?
【发布时间】:2016-03-05 15:19:18
【问题描述】:

我有一个类似这样的 REST API:

GET /zones - 列出所有区域

{
  "zones": [
    {
      "name": "zone 1",
      "persons": [
        0,
        2,
        3
      ],
      "counter" : 3
    },
    {
      "name": "zone 2",
      "persons": [
        1,
        5
      ],
      "counter" : 0
    }
  ]
}

POST /zones - 创建一个新区域

{
  "name": "zone 1",
  "persons": [
    0,
    2,
    3
  ]
}

删除 /zones/:id

删除一个区域

PUT /zones/:id

更新区域

现在,我终于有了这个:

GET /zones/increment_counter/:id

增加区域的计数器参数。

我正在使用 Angular,并且我正在为 Zone 对象定义一个工厂,它应该从此 REST API 中获取自身。

我见过this example,它几乎可以满足我的要求,除了增量操作,它不遵循 RESTful 准则。

我无法修改 REST API,所以我必须处理这个问题。我应该如何处理这些类型的端点?

另外,我应该使用服务还是只在我的区域工厂中定义一个方法(例如:zone.incrementCounter())直接查询服务器并增加计数器?

我习惯了 Java 对象,我只需要为 and the class will access the server's endpoints under the hood 类定义 getterssetters

最好的方法是什么?

【问题讨论】:

标签: javascript angularjs angular-ui-router angularjs-service angularjs-factory


【解决方案1】:

你试过ngResource吗?因为那是你应该开始的地方。

这是一个未经测试的 sn-p,可以为您提供要点。

工厂

angular.module('MyApplication')
    .factory('ZoneFactory', ['$resource', function($resource) {
        var url = 'www.example.com/api/zones';
        var paramDefaults = {};
        var methods = {
            'get': {
                'url': url,
                'method': 'GET'
            },
            'post': {
                'url':  url,
                'method': 'POST'
            },
            'delete': {
                'url':  url,
                'method': 'DELETE',
                'params': {
                    'id': '@id'
                }
            },
            'put': {
                'url':  url,
                'method': 'PUT',
                'params': {
                    'id': '@id'
                }
            },
            'increment': {
                'url':  url + '/increment_counter',
                'method': 'GET',
                'params': {
                    'id': '@id'
                }
            }
        };
        return $resource(url, paramDefaults, methods);
    }]);

控制器

angular.module('MyApplication')
    .controller('SomeController', ['ZoneFactory', function(ZoneFactory) {
        var mv = this;

        mv.newZone = {
            'name': '',
            'persons': [],
            'counter': 0
        };
        mv.zones = ZoneFactory.get();

        mv.createZone = function() {
            ZoneFactory.post({'zone': mv.newZone});
            mv.zones.push(mv.newZone);

            mv.newZone = {
                'name': '',
                'persons': [],
                'counter': 0
            };
        };
    }]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多