0

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

2
  • 1
    please remove the single quote from 'response' Commented Dec 14, 2014 at 15:04
  • I have already tried that Commented Dec 14, 2014 at 15:08

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked, but is there a way i can move interceptor to independent file ?
you can put it in myfile.js but make sure the script tag for it is above your app.js one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.