quma
quma

Reputation: 5743

Angular JS Interceptor to handle HTTP Error status

I use AngularJS for my application and ui-route. A service in my application looks like this:

(function() {
'use strict';

angular
    .module('myProject.myModule')
    .factory('myService', myService);

myService.$inject = ['$http', 'api_config'];

function myService($http, api_config) {
    var service = {
            myServiceMethod1: myServiceMethod1,
            ...
    };

    return service;

    ////////////

    function myServiceMethod1(params) {
        return $http.get(api_config.BASE_URL + '/path');
    }

Now I will implement an (global) intercetor in that way that any time a response status is HTTP 403 the interceptor should handle it. This interceptor should be globally. Thanks a lot!

Upvotes: 1

Views: 3057

Answers (1)

Florian
Florian

Reputation: 712

Try something like

angular
    .module('myProject.myModule')
    .config(['$httpProvider', function ($httpProvider) {

 $httpProvider.interceptors.push(['$q', '$location', function ($q, $location) {
        return {
            'responseError': function(response) {
                if(response.status === 401 || response.status === 403) {
                    $location.path('/signin'); // Replace with whatever should happen
                }
                return $q.reject(response);
            }
        };
    }]);
}]);

Upvotes: 3

Related Questions