0

I want to perform additional operation before calling http request(Ajax GET and POST)

suppose i have following code:

function CallHTTP()
{

    $.ajax({
        url: '/abcd/abcd',
        type: 'POST',
        success: function () {
            alert("Success");
        },
        error: function (arg1, arg2, arg3) {
            alert("error");
        }

    });

}

$(document).ready(function () {
    CallHTTP();
});

i want to handle above request using angularjs interceptor. is it possible ?

I tried following:

 angular.module('app', [])
          .config(['$httpProvider', function ($httpProvider) {
              $httpProvider.interceptors.push(['$location', '$q', function ($location, $q) {
                  return {
                      'request': function (request) {
                          console.log("abcd");
                          return request;
                      },
                      'responseError': function (response) {
                          if (response.status === 401) {
                              console.log("abcd2");
                              // do stuff
                          }
                          console.log("abcd1");
                          // otherwise, default behaviour
                          return $q.reject(response);
                      }
                  };
              }]);
          }]);

but above code doesn't execute when ajax call happens. how to achieve it ?

Thanks.

2
  • An interceptor intercepts a request/response exchange, but it doesn't perform it. You must use $http. docs.angularjs.org/api/ng/service/$http Commented Jul 6, 2017 at 12:59
  • if you want to do it with jquery, use jquery ajax events: $(document).bind("ajaxSend", function () { console.log('before request'); }); api.jquery.com/Ajax_Events Commented Jul 6, 2017 at 13:11

1 Answer 1

2

You are using jquery ajax call and your settings are in the angular interceptor. Use $http to make use of your angular settings.

Sign up to request clarification or add additional context in comments.

Comments

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.