Skip to content Skip to sidebar Skip to footer

Angular Ui Router Issue When Redirecting To A Template After Resolve() Throws Error

So It took me a very long time to understand this issue and get to a mcve. Here is the case : I'm trying to redirect a user to a login page when he's not authenticated (this is ver

Solution 1:

You need to call event.preventDefault() before you call $state.go().

See here: http://plnkr.co/edit/eUosIpdN7adJFxfDo3kV?p=preview

The main reason this error is occuring, as you have already identified, is that the template url 'views/login.html' doesn't exsit. You said that when you changed the template url from 'views/login.html' to 'login.html' everything worked, and this makes sense because that template does exist.

The reason you are seeing the infinite digest error is that each time you try to access the welcome state the auth resolver is throwing an error which triggers the $stateChangeError event like you would expect it too. Everything is fine up until the point when it tries to go to the login state. Attempting to transition to the login state fails because the template url 'views/login.html' doesn't exist, and this failure is causing your otherwise redirect to bring you back to the welcome state. You can see at this point that arriving back at the welcome state will restart the whole cycle and cause the infinite digest loop.

Simply ensuring that your template urls are correct should prevent this from happening, as you have already discovered.

Solution 2:

I have had the same problem and this is how I solved it

.run(function($rootScope, $state) {
        $rootScope.$on('$stateChangeError', function() {
          // Redirect user to our login page$state.go('auth.login');
        });
      });

Below I pasted my entire page so you can see how it all works together 'use strict';

angular.module('mean.pdash').config(['$stateProvider',

function($stateProvider) {
  // Check if the user is connectedvar checkLoggedin = function($q, $timeout, $http, $location) {
    // Initialize a new promisevar deferred = $q.defer();
    $http.get('/loggedin').success(function(user) {
      // Authenticated
      console.log(user);
      if (user !== '0') {
        $timeout(deferred.resolve);
      } else {
        $timeout(deferred.reject);
      }
    });

    return deferred.promise;
  };
  $stateProvider.state('pdash', {
    url: '/',
    templateUrl: 'pdash/views/index.html',
    controller: 'PdashController',
    resolve: {
      checkLoggedin: checkLoggedin
    }
  });
}
])
  .run(function($rootScope, $state) {
    $rootScope.$on('$stateChangeError', function() {
      // Redirect user to our login page$state.go('auth.login');
    });
  });

Post a Comment for "Angular Ui Router Issue When Redirecting To A Template After Resolve() Throws Error"