Rudy
Rudy

Reputation: 210

Intercepting jQuery ajax calls in Angular

I'm using CouchDBs bundled $.couch API within an Angular application. I'd like to intercept ALL ajax requests, whether from Angular's $http service or jQuery's $.ajax (which is what $.couch uses). I have an interceptor set up in angular as follows:

$httpProvider.interceptors.push(['$location', '$q',  function($location, $q) {
      return {
          'request': function(request) {
              return request;
          },
          'responseError': function(response) {
              if (response.status === 401) {
                console.log("UH OH")
              }
              // otherwise, default behaviour
              return $q.reject(response);
          }
      };
  }]);

and what I've noticed is that requests and response errors from the $http angular service are caught, but the $.ajax calls and errors are not. So my question is, what's the proper way for me to intercept all ajax requests in my app from in and out of angular? Ideally I'd like to have one handler for both.

Upvotes: 0

Views: 1094

Answers (1)

netalex
netalex

Reputation: 457

don't have a true answer, but surely interceptors are an array of property specific of angular's $httpProvider object. None similar is present in jquery. No way that code of yours could know something about $.ajax calls. I don't know, maybe you could wrap jquery ajax in a promise, re-creating something like interceptors.

in this post is described how interceptors are made under the hood in angular. This could be an hint for you. what are interceptors

more info

Hope it helps!

Upvotes: 0

Related Questions