Hacker News new | ask | show | jobs
by Kiro 4752 days ago
Everyone keeps saying I should use Restangular instead of ngResource but so far I haven't seen any good reasons to. Anyone care to enlighten me?
2 comments

Heh.. I still don't know yet.

I'm building a fairly big Django/Angular project with ngResource and have been trying to replace it with Restangular, which has a nice API. But both have pros and cons:

What I like about ngResource is that returned data is automagically filled in as soon as the AJAX request completes. I can do this:

  function controller(Resource) {
    $scope.thing = Resource.get(); // here $scope.thing is an empty object, will be filled in as soon as data arrives

    $scope.do = function() { alert ($scope.thing.name); }
  }
Restangular returns promises instead, so to replicate the above code I'll have to do

  function controller(Restangular) {
    $scope.thing = Restangular.one('thing', 1).get();
    // $scope.thing is a promise, I can't directly access its members in the controller, but since angular templating has native support of promises, I can use {{thing.name}} there.

    $scope.do = function() {
      $scope.thing.then(function(thing) {
        alert(thing.name);
      }
    }
  }
-- or --

  function controller(Restangular) {
    // I think that's ugly
    Restangular.one('thing', 1).get().then(function(thing) {
      $scope.thing = thing;
    }

    // $scope.do will be the same as in the ngResource example
  }
Conclusion: Restangular has a nice API - but magically filling list/object is ngResource major selling point.

What I'd like from both is a nice getOrCreate method for elements, where it POSTs if the object doesn't have an ID set, otherwise sends a PUT. In CRUD forms I try to use the same controller for both "new" and "edit" actions, and I don't want to check the presence of ID and call the appropriate method every time.

Also, if Angular could handle REST data with a higher level library inspired by Ember.Data, I could die a happy programmer.

I haven't used either, I have used only $http so far but I have observed two important differences:

- Support for wrapped responses: ngResource expects that you return an array for GET, so you need to return [objects]. See https://github.com/mgonto/restangular#my-response-is-actuall...

So, if you return something like `{meta: ..., data: [objects]}`, you are out of luck. Does anyone know a work around for ng-resource? I am using tastypie server-side which returns wrapped responses.

- restangular uses promises for callback, so you can do foo.get().success(function (){}) just like $http, while ng-resource uses jquery like foo.get(function () {})