Skip to content

Nested decoupled service: how to? #1381

Open

Description

@destegabry

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);
    };
  });

Activity

  1. daviesgeek commented on Jun 16, 2016

    @daviesgeek
    Collaborator

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

  2. alexjose commented on Dec 9, 2016

    @alexjose

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

  3. ashgibson commented on Jan 12, 2017

    @ashgibson

    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'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions