Usage of interceptor within $resource

How do I use an interceptor within an Angular $resource?

My JSON structure:

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

My controller is the following:

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

My services, and what I tried using the interceptor object:

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

I read $resource, and it seems like this should work, but it doesn't, so I'm mis-understanding. Any suggestions?

Answers:

Answer

Your service is improperly formed. There are curly braces and parentheses int the wrong places.

Here is the correct version (modified slightly so that I could get it to run: 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
        }
    }

    );
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.