Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing Angularjs $resource default parameters in a service

Tags:

angularjs

Suppose I have

 angular.module('clientApp').factory('CreditCardResource', function($resource) {
   return $resource('/user/:userId/card/:cardId',
    {cardId:'@id'}, {
     charge: {method:'POST', params:{charge:true}}
    });
 });

I want to be able to have a CreditCardResource asociated to a certain userId, so that every time I call CreditCardResource.query() y get the cards related to that user. I dont want to call CreditCardResource.query({userId : 123}) every time. And I want the Resource to stay as a service.

I would like to do something like: CreditCardResource.defaultParams.userId = '123' in my controller.

What is the best way to aproach this problem?

like image 983
martinpaulucci Avatar asked Nov 09 '12 16:11

martinpaulucci


4 Answers

Since version 1.1.2 dynamic default parameters are supported

https://github.com/angular/angular.js/commit/cc42c99bec6a03d6c41b8e1d29ba2b1f5c16b87d

Basically, instead of:

params: {
    apiKey: user.getApiKey()
}

You use:

params: {
    apiKey: function() {
        return user.getApiKey();
    }
}
like image 156
martinpaulucci Avatar answered Nov 03 '22 16:11

martinpaulucci


Angular Resource provides a Resource.bind() method for this exact circumstance (I'm on v1.0.3).

In your case, your code should be:

var BoundCreditCard = CreditCard.bind({userId: '123'});

// Performs a GET on /user/123/card/456
var card = BoundCreditCard.get({cardId: "456"});
like image 22
Kevin Stone Avatar answered Nov 03 '22 15:11

Kevin Stone


You can perhaps decorate your instance of $resource.query()? This is a generic, non-angular example but hopefully makes the point. 'someObj' in your case would be $resource, and your controller can set the value for 'defaultValue'.

  var proxiedFn, someObj;

  someObj = {
    someFn: function(valueA, valueB) {
      console.log("Called with " + valueA + " and " + valueB);
    }
  };

  someObj.someFn('foo', 'bar'); /* before the proxy */
  proxiedFn = someObj.someFn;

  someObj.someFn = function(valueB) {
    return proxiedFn(this.defaultValue, valueB);
  };

  someObj.defaultValue = 'boz';
  someObj.someFn('bar'); /* after the proxy with default value */
like image 45
Roy Truelove Avatar answered Nov 03 '22 16:11

Roy Truelove


angular.module('clientApp')
.factory('User', ['$resource', 'UserCard',
    function ($resource, UserCard) {
        var User = $resource(
            "user/:id",
            {id: "@id" },
            {
                'save': {method: 'PUT'},
                'add': {method: 'POST'}
            }
        );
        User.prototype.getCards = function (params, callback) {
            UserCard.prototype.userId = this.id;
            params.userId = this.id;
            return UserCard.query(params, callback);
        };
        return User;
    }])
.factory('UserCard', ['$resource',
    function ($resource) {
        return $resource(
            "user/:userId/card/:id",
            {userId: '@userId', id: "@id" },
            {
                'save': {method: 'PUT'},
                'add': {method: 'POST'}
            }
        );
    }])
.controller('TestCtrl', ['User',
    function (User) {
        // GET user/123
        var user = User.get({id: 123}, function () {
            // GET user/123/card/321
            var card = user.getCard({id: 321}, function () {
                card.someAttribute = 'Some value';
                // PUT user/123/card/321
                card.$save();
            });
        });
    }])
;

Check my code. In that way I get cards already associated with user, so card.$save() or card.$query() doesn't need to pass userId nor at parameters, nor at card's properties.

like image 28
zaqf Avatar answered Nov 03 '22 15:11

zaqf