9

如何interceptor在 Angular 中使用 an $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,似乎这应该有效,但它没有,所以我误解了。有什么建议么?

4

1 回答 1

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
        }
    }

    );
});
于 2013-10-09T01:18:44.230 回答