Last active
January 3, 2016 11:39
-
-
Save xtbl/8457706 to your computer and use it in GitHub Desktop.
AngularJS $interceptor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app.js | |
// http://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/ | |
// http://blog.brunoscopelliti.com/http-response-interceptors | |
//any 404 error clean cookies and sends the user to login | |
var interceptor = ['$rootScope', '$q', '$location', '$cookieStore', function ($rootScope, $q, $location, $cookieStore) { | |
function success(response) { | |
return response; | |
} | |
function error(response) { | |
var status = response.status; | |
if (status == 401) { | |
$cookieStore.remove('user'); | |
$rootScope.user = null; | |
return $location.path('/login'); | |
} | |
// otherwise | |
return $q.reject(response); | |
} | |
return function (promise) { | |
return promise.then(success, error); | |
} | |
}]; | |
$httpProvider.responseInterceptors.push(interceptor); | |
}]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment