Angularjs: interceptor redirection creates double rendering

I am stuck in this strange behavior. None of the Google hits seem to mention a similar case, so I assume I'm doing something serious.

My interceptor responds to status 401 and redirects to the corresponding route, but at the same time it displays the previous route. Therefore, I have a very ugly flash of one pattern and another. I'm just trying to verify my authentication: if authenticated, then visualize the table, otherwise change the login form. It redirects to the login form, but still the table template blinks for a second.

angular.module('Basal', ['ngRoute', 'Basal.users'])

.config(function($routeProvider, $locationProvider, $httpProvider) {
  $locationProvider.html5Mode(true);
  $httpProvider.interceptors.push('authInterceptor');
  $routeProvider.
    when('/', {
      templateUrl: '/tpl/table.html',
      controller: 'MainCtrl'
    }).
    when('/login', {
      templateUrl: '/tpl/login-form.html',
      controller: 'MainCtrl'
    }).
    otherwise({
      redirectTo: '/'
    });
});


angular.module('Basal.users', [])
.controller('MainCtrl', function($scope, getJson) {

  getJson.fetch(function (d){
    $scope.computers = d;
    });
})

.factory('getJson', function($http, $location) {
  return {
    fetch: function (c) {
      $http.get("/json")
        .success(function(data) {
          console.log("getJson: Success!");
          c(data);
        })
        .error(function() {
          console.log("getJson: Failure!");
        });
    }
  }
})

.factory('authInterceptor', function($q, $location) {
  return {
    'responseError': function(response) {
      if (response.status === 401) {
        $location.path('/login');
      }
      return $q.reject(response);
    }
  }
});

, '/' Angular, : - , - JSON.

! - . , , , , Angular . , .

, . . , JSON 401 , . . - . ? , ? Angular ?

, otherwise $routeProvider . URL-, 404 , Angular . ? URL Angular, reload , 404 . 404 ? otherwise?

.

+4

Source: https://habr.com/ru/post/1538400/


All Articles