【问题标题】:Handle ajax call using angularjs使用 angularjs 处理 ajax 调用
【发布时间】:2017-07-06 12:55:08
【问题描述】:

我想在调用 http 请求之前执行额外的操作(Ajax GET 和 POST)

假设我有以下代码:

function CallHTTP()
{

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

    });

}

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

我想使用 angularjs 拦截器处理上述请求。有可能吗?

我尝试了以下操作:

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

但是当发生 ajax 调用时,上面的代码不会执行。如何实现?

谢谢。

【问题讨论】:

标签: javascript jquery angularjs ajax


【解决方案1】:

您正在使用 jquery ajax 调用,并且您的设置在角度拦截器中。使用 $http 来使用您的角度设置。

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2016-06-13
    • 1970-01-01
    相关资源
    最近更新 更多