8

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?

1
  • 2
    so little is known about angular i find it entertaining sometimes. here we are having problems that would be SO easy to solve in just about any other main stream language :) Commented Nov 9, 2012 at 19:29

4 Answers 4

8

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note sure why this was voted down. This commit provides useful functionality.
6

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

3 Comments

Could not find the documentation, could you please provide a link ? The syntax does not even make sense to me.
Sorry, I ported it from coffeescript for this post and forgot to add back the brackets for the parameters.
Unfortunately bind doesn't work with actions on a resource returned from an api call. Here's an example of where you lose your default params, gist.github.com/log0ymxm/7029656 It would be nice to update angular-resource to remember default parameters in this situation.
1

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 */

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.