R3W
R3W

Reputation: 33

Passing params from controller to service

I have a controller:

function BenefitsController($scope, $state, Authentication, UsersService) {

  //this
  var vm = this;

  var username = Authentication.username;

  // get benefits
  UsersService.listItems(function (resource, headers) {
    vm.items = resource;
}

I've defined a user service, and then.

  UsersService.$inject = ['$resource'];

  function UsersService($resource) {
    var Users = $resource('/api/users', {}, {
      update: {
        method: 'PUT'
      },
      listItems: {
        method: 'GET',
        isArray: true,
        url: '/api/users/benefits/:username',
        params: {
          provider: '@username'
        }
      }
    });

    return Users;
  }

My question is, how do I send the username through the controller to the service. Is this even the right thing to do?

Upvotes: 0

Views: 52

Answers (1)

BąQ
BąQ

Reputation: 306

Try something like this:

function UsersService($resource) {
    var Users = $resource('/api/users', {}, {
      update: {
    method: 'PUT'
      },
      listItems: {
        method: 'GET',
        isArray: true,
        url: '/api/users/benefits/:username',
        params: {
          username: '@username'
        }
      }
    });

    return Users;
  }

And then you can call:

UsersService.listItems({username: username }, function (resource, headers) {
    vm.items = resource;
}, 
function(err) {
    // Error handling
});

jsFiddle: jsfiddle.net/gtrwzsn1/3079

Upvotes: 2

Related Questions