Feng erdong's Blog

Life is beautiful

Several Ways to Define Ajax Interceptors in AngularJS

| Comments

Original blog: Using Response Interceptors to Show and Hide a Loading Widget

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var myApp = angular.module("myApp", []);
myApp.config(['$httpProvider',
    function ($httpProvider) {
        var $http,
            interceptor = ['$q', '$injector',
                function ($q, $injector) {
                    function success(response) {
                        // get $http via $injector because of circular dependency problem
                        $http = $http || $injector.get('$http');
                        if ($http.pendingRequests.length < 1) {
                            console.log('ajax cal respond with success');
                        }
                        return response;
                    }

                    function error(response) {
                        console.log('x', response);
                        // get $http via $injector because of circular dependency problem
                        $http = $http || $injector.get('$http');
                        if ($http.pendingRequests.length < 1) {
                            console.log('ajax call respond with error');
                        }
                        return $q.reject(response);
                    }

                    return function (promise) {
                        console.log('before send ajax request');
                        return promise.then(success, error);
                    };
                }
            ];

        $httpProvider.responseInterceptors.push(interceptor);
    }
]);

Check out the demo

Comments