user3714598 user3714598 - 9 months ago 89
AngularJS Question

Handle redirects in angularjs $http

Im using angularjs http service in my app. and I noticed this in the website

If the AJAX call succeeds (the server sends back an HTTP code between
200 and 209), the function passed to the success() function is
executed. If the AJAX call fails (all other codes except for
redirects), the function passed to the error() method is executed.

obviously, the redirects status code isnt part of success neither error callbacks.
So how are we going to handle redirects?

This is what my script does, get data from server using http get. If session expires, server returns 302 status code. I should catch that status code then redirect the page to login.

app.controller('GraphController', function($scope, $http, localStorageService, $interval) {
$scope.GraphData = [{"key":"in","values":[]},{"key":"out","values":[]}];

$scope.pollStats = function() {
$http.get('/statistics/getStat').success(function(lastData, status, headers) {
if (status==302) {
//this doesn't work
//this doesn't work either
}else if (status==200) {

Obviously my script wont work because success callback cant handle redirects. So how are we supposed to handle that?

Answer Source

Please note that this is specific to my project.

Goal: Catch 302 status code and redirect the page (to login in my case).

Result: In firebug, I could see that the response code is 302 but then I found out that angularjs returns 200 by simply printing the value of status (response.status). So at first you'd thought that you're hopeless. But in my case, what I did was get the data (, look for the string that could be only found in my login page. Then that's it. problem solved :D

The idea was taken here.

Here's the code

app.factory('redirectInterceptor', function($q,$location,$window){
    return  {
        if (typeof === 'string' &&"My Login Page")>-1) {
            $window.location.href = "/login.html";
            return $q.reject(response);
            return response;


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