在Angular JS中为$ resource添加自定义方法

时间:2015-06-19 13:33:02

标签: angularjs

我编写了一个自定义方法来调用我的API传递一些额外的参数,但是我收到以下错误: TypeError test.testing不是函数。 我按照这里的代码进行了操作:https://docs.angularjs.org/api/ngResource/service/ $ resource

这是我使用的代码,例如$ save工作正常。

我使用的是版本1.4.1。

services.factory('Calendar',function($resource){
    return $resource('/api/calendar/:id',{
        update: {
            method: 'PUT'
        },
        testing: {
            method: "POST", params:{charge:true}
        }
    });
});

function( $scope, Calendar ) {

        var test = new Calendar();
        test.title = "hello";
        test.$testing();
        ...
}

1 个答案:

答案 0 :(得分:1)

原因是因为您没有完全遵循文档中的示例。参见:

angular.module('testApp', [])
  .factory('CreditCard', creditCard)
  .factory('Calendar', calendar);

function creditCard() {
  return $resource('/user/:userId/card/:cardId',
      {userId:123, cardId:'@id'}, {
      charge: {method:'POST', params:{charge:true}}
  });
}

function calendar() {  
  return $resource('/api/calendar/:id',
    {id: 200},
    {
      update: {
          method: 'PUT'
      },
      testing: {
          method: "POST", params:{charge:true}
      }
  });
}

正如您所看到的,我添加了第二个对象参数{id:200},它告诉ng-resource为了正确填充/api/calendar/:id,需要从属性id中取出那个对象并使用它的价值。