What is the equivalent of jQuery ajax beforeSend in Angularjs?

a 夏天 提交于 2019-11-28 19:36:06

By default Angular does not provide beforeSend and complete but you can implement them by using interceptors. Here is my implementation:

(function() {
    var app = angular.module("app");

    app.factory("interceptors", [function() {

        return {

            // if beforeSend is defined call it
            'request': function(request) {

                if (request.beforeSend)
                    request.beforeSend();

                return request;
            },


            // if complete is defined call it
            'response': function(response) {

                if (response.config.complete)
                    response.config.complete(response);

                return response;
            }
        };

    }]);

})();

Then you have to register your interceptor like this:

    (function () {
        var app = angular.module('app', ['ngRoute']);


        app.config(["$routeProvider", "$httpProvider", function ($router, $httpProvider) {    

            // Register interceptors service
            $httpProvider.interceptors.push('interceptors');

            $router.when("/", { templateUrl: "views/index.html" })


            .otherwise({ redirectTo: "/" });        
        }]);
    })();

After this code you can use it like this:

var promise = $http({
    method: 'POST',
    url: constants.server + '/emails/send',
    data: model,
    beforeSend: function() {
        model.waiting = true;
    },
    complete: function() {
        model.waiting = false;
    }
});

You can use interceptors. Search for the word interceptor into the Angular $http documentation

As the documentation says : For purposes of global error handling, >authentication, or any kind of synchronous or asynchronous pre-processing of >request or postprocessing of responses

Here is a good Fiddle Example displaying a loading gif before the ajax call is sent.

EDIT

As Satpal commented, $httpProvider.responseInterceptors used in the Fiddle is deprecated. You should use $httpProvider.interceptors instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!