与 $resource 的不同点

Restangular一些区别于$resource的特性:

  • 使用 promises. Instead of doing the "magic" filling of objects like $resource, it uses promises.
  • 可以在 $routeProvider.resolve使用. As Restangular returns promises, you can return any of the methods in the $routeProvider.resolve and you'll get the real object injected into your controller if you want.
  • 没有 $resource 错误. Restangular doesn't have problem with trailing slashes, additional : in the URL, escaping information, expecting only arrays for getting lists, etc.
  • 支持所有 HTTP 方法.
  • 支持 ETag 开箱. You don't have to do anything. ETags and If-None-Match will be used in all of your requests
  • 支持自联元素 If you receive from the server some item that has a link to itself, you can use that to query the server instead of writing the URL manually.
  • 不必为每次请求创建 $resource 对象. Each time you want to do a request, you can just do it using the object that was returned by Restangular. You don't need to create a new object for this.
  • 你不用书写和记录任何URL. With $resource, you need to write the URL Template. In here, you don't write any urls. You just write the name of the resource you want to fetch and that's it.
  • 支持嵌套的RESTful资源. If you have Nested RESTful resources, Restangular can handle them for you. You don't have to know the URL, the path, or anything to do all of the HTTP operations you want.
  • Restangular可以创建自己的方法. You can create your own methods to run the operation that you want. The sky is the limit.
  • 支持包裹响应. If your response for a list of element actually returns an object with some property inside which has the list, it's very hard to use $resource. Restangular knows that and it makes it easy on you. Check out https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case
  • 你可以使用Restangular对象轻松创建你自己的URLs. Restangular lets you create a Restangular object for any url you want with a really nice builder.

开一个这功能的快捷实:

// Restangular returns promises
Restangular.all('users').getList()  // GET: /users
.then(function(users) {
  // returns a list of users
  $scope.user = users[0]; // first Restangular obj in list: { id: 123 }
})

// Later in the code...

// Restangular objects are self-aware and know how to make their own RESTful requests
$scope.user.getList('cars');  // GET: /users/123/cars

// You can also use your own custom methods on Restangular objects
$scope.user.sendMessage();  // POST: /users/123/sendMessage

// Chain methods together to easily build complex requests
$scope.user.one('messages', 123).one('from', 123).getList('unread');
// GET: /users/123/messages/123/from/123/unread