Showing posts with label Redirect Interceptor. Show all posts
Showing posts with label Redirect Interceptor. Show all posts

Saturday, January 14, 2017

Implement Redirect Interceptor For All Http Call - Angular JS

Download resources from here


<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="angular-resource.js"></script>

<div data-ng-app="myApp" data-ng-controller="MyCtrl">[[dataFromAngularJS]]</div>

<script type="text/javascript">
    var app = angular.module('myApp', ['ngResource'], function ($interpolateProvider) {
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    });
    app.config(['$httpProvider', '$controllerProvider', function ($httpProvider, $controllerProvider, $window) {
        $httpProvider.interceptors.push('redirectInterceptor');
    }])
    .run(function ($rootScope, $window) {
        console.log("MY_APP START RUNNING");
        $rootScope.baseUrl = "/";
    })
    .factory('redirectInterceptor', function ($q, $location, $window, $rootScope) {
        return {
            response: function (response) {
                console.log("GOT DATA VIA AJAX CALL");
                console.log(response);
                return response;
            },
            responseError: function(response) {
                console.log("GOT ERROR VIA AJAX CALL");
                console.log(response);
                response.data = "ERROR";
                return $q.reject(response);
            }
        }
    });

    app.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.dataFromAngularJS = "Data From Angular JS";

        $http.get('data.html').
        success(function(response, status, headers, config) {
            $scope.dataFromAngularJS = "Success=" + response;
        }).
        error(function(response, status, headers, config) {
            $scope.dataFromAngularJS = "Error=" + response;
        });
    }]);
</script>