Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - handling 401's for entire app

Tags:

angularjs

I have the following code in one of my Controllers to handle a 401 gracefully:

ChannelsService.query(function(response) {
    $scope.channels = response;
}, function(error) {
    if (error.status == 401) {
        $state.go('login');
    }

});

and my corresponding service:

myServices.factory('ChannelsService', function ($resource) {
    return $resource('/channels', {}, {
        query: { method: 'GET', isArray: true },
        create: { method: 'POST' }
    })
});

I would like to know how to handle 401's globally so that I don't have to work this logic into every controller. Is it an interceptor that I need and if so could someone share some code?

Thanks

like image 250
tommyd456 Avatar asked May 18 '14 08:05

tommyd456


1 Answers

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

You can add an interceptor to the $httpProvider when configuring your application

app.config(['$httpProvider', function($httpProvider) {

    $httpProvider.interceptors.push(function($q) {

        return {

            'responseError': function(rejection){

                var defer = $q.defer();

                if(rejection.status == 401){
                    console.dir(rejection);
                }

                defer.reject(rejection);

                return defer.promise;

            }
        };
    });

}]);

As the name already suggests, this will intercept each request and call the provided function if there is a responseError (You could add interceptors for succeeded requests, too)

For further information, see the $http docs

like image 144
Wottensprels Avatar answered Sep 22 '22 01:09

Wottensprels