-1

我有一個REST API,它有這樣的事情:將AngularJS與非RESTful API集成的最佳方法是什麼?

GET /區 - 列出所有區域

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

POST /區 - 創建一個新的區域

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

DELETE/zones /:編號

刪除區

PUT /區/:ID

更新區域

,現在,終於我有這樣的:

GET /區/ increment_counter /:ID

它遞增區域的計數器參數。

我正在使用Angular,並且正在爲Zone對象定義一個工廠,該工廠應該從此REST API自己提供。

我看過this example,除了增量操作,它不符合RESTful準則外,它幾乎滿足了我的要求。我不能修改REST API,所以我不得不處理這個。我應該如何處理這些類型的端點?

另外,我應該使用服務還是我可以在我的Zone工廠(例如:zone.incrementCounter())中定義一個方法,它直接查詢服務器並增加計數器?

我用Java對象,在這裏我只需要定義干將制定者一類and the class will access the server's endpoints under the hood

這是最好的方法是什麼?

+0

FYI:http://vvv.tobiassjosten.net/development/your-api-is-not-restful/ :) – sp00m

回答

1

你試過ngResource?因爲那是你應該開始的地方。

這裏有一個未經測試的片段給你的要點。

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 
      }; 
     }; 
    }]); 
相關問題