$http interceptor

by Rishi Kumar

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script>
<div ng-controller="x">
    <ul>
        <li ng-repeat="ping in pings track by $index">{{ping}}</li>
    </ul>
</div>

JavaScript

angular.module('analytics', [])
    .factory('myHttpInterceptor', ['$q', function ($q, dependency1, dependency2) {
    var s = 0;
    return {
        // optional method
        'request': function (config) {
            // do something on success
            s = (new Date());
           	if(config.method == "POST"){
            		config.data.token = "ABCDE1"
            }else{
            	config.url = config.url + "&token='ABCDE1'"
            }
            return config || $q.when(config);
        },

        // optional method
        'requestError': function (rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise;
            }
            return $q.reject(rejection);
        },



        // optional method
        'response': function (response) {
            // do something on success
            response.duration = (new Date()) - s;
            return response || $q.when(response);
        },

        // optional method
        'responseError': function (rejection) {
           
            return $q.reject(rejection);
        }
    };
}])
    .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
}])
    .controller('x', ['$http', '$interval', '$scope', function ($http, $interval, $scope) {
    $scope.pings = [];
    //$interval(function () {
        $http.get("/echo/json/data?name='Rishi'",{abc: 123}).then(function (r) {
            console.log(r);
            $scope.pings[$scope.pings.length] = r.duration;
        });
    //}, 1000);
}]);


angular.bootstrap(document, ['analytics']);