restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Nested decoupled service: how to?

Open destegabry opened this issue 8 years ago • 3 comments

I'm trying to follow the documentation and after reading #139 and #1254 I'm more confused than ever. I have some tables on my DB, let's say User, Customer and UserCustomer (which implements an n:n relation between User and Customer). I have set up endpoints in my server at /user/[id], /customer/[id] and /user/[iduser]/customer/[idcustomer] I can CRUD on User and Customer tables using the Restangular.service syntax:

angular.module('...')
  .factory('User', function (Restangular) {
    return Restangular.service('user');
  })
  .factory('Customer', function (Restangular) {
    return Restangular.service('customer');
  })

In my User factory I would like to define a getCustomer method which populates an user instance with a customers variable, pointing to a collection of Customer. Seems I can do something like:

angular.module('...')
  .factory('User', function (Restangular) {
    Restangular.extendModel('user', function(model) {
      if (model.customers) {
        Restangular.restangularizeCollection(null, model.customers, 'customer');
      }
      return model;
    });
    return Restangular.service('user');
  });

but can't figure out how to use it in a controller! I'd like to do something like:

angular.module('...')
  .controller('...', function ($scope, User) {
    User.getList().then(function (users) {
      $scope.users = users;
      angular.forEach(users, function (user) {
        user.customers.getList();
      });
    });
    $scope.addUserCustomerAssociation = function (user, customer) {
       user.customers.post(customer.id);
    };
   $scope.removeUserCustomerAssociation = function (user, customer) {
       user.customers.remove(customer.id);
    };
  });

destegabry avatar May 31 '16 09:05 destegabry

You should be able to do that in a controller. What isn't working?

daviesgeek avatar Jun 16 '16 23:06 daviesgeek

I am also trying to figure this out. How to build Nested decoupled services?

alexjose avatar Dec 09 '16 05:12 alexjose

That should be working, the only thing to note is that because you are passing 'null' in a the first parameter to restangularizeCollection, it won't build a nested url for you e.g. '/users/1/customers'.

ashgibson avatar Jan 12 '17 04:01 ashgibson