自定义服务中的Angularjs $ resource默认参数

时间:2023-01-21 19:45:04

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.

我希望能够将CreditCardResource与某个userId联系起来,这样每次我调用CreditCardResource.query()时都会获得与该用户相关的卡片。我不想每次都调用CreditCardResource.query({userId:123})。我希望资源保留为服务。

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

我想做一些像:CreditCardResource.defaultParams.userId ='123'在我的控制器中。

What is the best way to aproach this problem?

解决这个问题的最佳方法是什么?

4 个解决方案

#1


6  

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

Angular Resource为这种确切的环境提供了Resource.bind()方法(我在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"});

#2


7  

Since version 1.1.2 dynamic default parameters are supported

从1.1.2版开始,支持动态默认参数

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

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

Basically, instead of:

基本上,而不是:

params: {
    apiKey: user.getApiKey()
}

You use:

你用:

params: {
    apiKey: function() {
        return user.getApiKey();
    }
}

#3


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

你可以装饰你的$ resource.query()实例吗?这是一个通用的,无角度的例子,但希望能说明问题。在你的情况下,'someObj'将是$ resource,你的控制器可以设置'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 */

#4


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.

检查我的代码。通过这种方式,我获得了已经与用户关联的卡片,因此卡片。$ save()或卡片。$ query()不需要传递userId,也不需要传递参数,也不需要传递卡片的属性。

#1


6  

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

Angular Resource为这种确切的环境提供了Resource.bind()方法(我在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"});

#2


7  

Since version 1.1.2 dynamic default parameters are supported

从1.1.2版开始,支持动态默认参数

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

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

Basically, instead of:

基本上,而不是:

params: {
    apiKey: user.getApiKey()
}

You use:

你用:

params: {
    apiKey: function() {
        return user.getApiKey();
    }
}

#3


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

你可以装饰你的$ resource.query()实例吗?这是一个通用的,无角度的例子,但希望能说明问题。在你的情况下,'someObj'将是$ resource,你的控制器可以设置'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 */

#4


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.

检查我的代码。通过这种方式,我获得了已经与用户关联的卡片,因此卡片。$ save()或卡片。$ query()不需要传递userId,也不需要传递参数,也不需要传递卡片的属性。