在$ resource中使用拦截器

时间:2013-09-03 01:47:17

标签: javascript angularjs

如何在Angular interceptor中使用$resource

我的JSON结构:

var dgs = [{id    :1,
            driver:'Sam',
            type:  'bus',
            segments:[{id:1,origin:'the bakery',arrival:'the store'},
                      {id:2,origin:'the store' ,arrival:'somewhere'}]
            },
            { ... },
            { ... }
          ];

我的控制器如下:

function dgCtrl($scope,$http,DriveGroup,Segment) {
  $scope.dgs = DriveGroup.query(function()
    // Code below may belong in a response interceptor?
    for (var i=0;i<$scope.dgs.length;i++) {
      var segments = $scope.dgs[i].segments;
      for (var j=0;j<segments.length;j++) {
        segments[j] = new Segment(segments[j]);
      }
    }
  });

我的服务以及我尝试使用interceptor对象的内容:

angular.module('dgService',['ngResource']).
  factory("DriveGroup",function($resource) {
    return $resource(
      '/path/dgs',
      {},
      {update:{method:'PUT'})
      {fetch :{method:'GET',
               // This is what I tried.
               interceptor:{
                 response:function(data) {
                   console.log('response',data);
                 },
                 responseError:function(data) {
                   console.log('error',data);
                 }
               },
               isArray:true
              }
    );
});

我读过$resource,看起来这应该有用,但事实并非如此,所以我误解了。有什么建议吗?

1 个答案:

答案 0 :(得分:6)

您的服务不正确。在错误的地方有花括号和圆括号。

这是正确的版本(略有修改,以便我可以运行它: http://jsfiddle.net/roadprophet/VwS2t/

angular.module('dgService', ['ngResource']).
factory("DriveGroup", function ($resource) {
    return $resource(
        '/', {}, {
        update: {
            method: 'PUT'
        },
        fetch: {
            method: 'GET',
            // This is what I tried.
            interceptor: {
                response: function (data) {
                    console.log('response in interceptor', data);
                },
                responseError: function (data) {
                    console.log('error in interceptor', data);
                }
            },
            isArray: false
        }
    }

    );
});