jeffsebring / angular-wp-api

An AngularJS Client for WP-API
124 stars 15 forks source link

Use Restangular instead of ngResource #14

Closed marklagendijk closed 2 years ago

marklagendijk commented 9 years ago

The current approach with ngResource forces you to use the ugly :param1/:param2 approach. I think it would be better to use Restangular instead. With Restangular you could create a service like this:

module.factory('wpAPIResource', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(wpAPIData.base);
    RestangularConfigurer.setDefaultHeaders({ 'X-WP-Nonce': wpAPIData.nonce });
  });
});

And then use it like this (example taken from Restangular README):

// Restangular returns promises
wpAPIResource.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');
jeffsebring commented 9 years ago

Thank you. This looks interesting. It will take a bit of time for me to dig into it and consider a v2.

marklagendijk commented 9 years ago

Since I posted this, I have applied this approach to a project which I am working on, and it is working great!

Some examples:

// GET
$scope.myEntities = myApi
  .all('myPlugin/myEntities')
  .getList()
  .$object;

// POSTing a form
if($scope.myForm.$valid){
  myApi.all('myPlugin/myEntities')
    .post($scope.myEntity)
    .then(function(){
      $scope.saved = true;
    });
}