user3561092
user3561092

Reputation: 47

Angularjs interceptor causes error

Im trying to create an interceptor for my sample angular.js app. Here's my config code:

  .config(function ($routeProvider, $httpProvider) {
  $routeProvider
    .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
  $httpProvider.interceptors.push('failedRequestInterceptor');

});

and my interceptor

angular.module('sandboxApp').factory('failedRequestInterceptor', function ($q) {
return {
    'response': function (config) {
        console.log("test");
    }
}

});

it displays "test" string in my console, but immidiatly after that i got error "response is undefined" and application fail's to load.

Perhaps this has something to do with using yeoman and tools included with it, here is exact error text from console :

Error: response is undefined handleRequestFn/<@http://localhost:9000/bower_components/angular/angular.js:16002:11 processQueue@http://localhost:9000/bower_components/angular/angular.js:13137:27 scheduleProcessQueue/<@http://localhost:9000/bower_components/angular/angular.js:13153:27 $RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:9000/bower_components/angular/angular.js:14353:16 $RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:9000/bower_components/angular/angular.js:14169:15 $RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:9000/bower_components/angular/angular.js:14457:13 done@http://localhost:9000/bower_components/angular/angular.js:9614:36 completeRequest@http://localhost:9000/bower_components/angular/angular.js:9804:7 requestLoaded@http://localhost:9000/bower_components/angular/angular.js:9745:1

return logFn.apply(console, args);

Upvotes: 0

Views: 821

Answers (1)

Ben Diamant
Ben Diamant

Reputation: 6206

Please follow this method of code:

Interceptor function:

var interceptor = function ($q, $location) {
    return {
        response: function (result) {
            console.log(result);
            return result;
        }
    }
};

Interceptor injection:

angular.module('app', [])
.config(function ($httpProvider) {
    $httpProvider.interceptors.push(interceptor);
});

Upvotes: 2

Related Questions