4

I'm loading states dynamically based on the current user role. But when the page is refreshed it takes to the 404 page. Also in $stateChangeStart event fromState.name is blank.

Is there a way to go to the state before refresh button was clicked? Should I store the state before refresh is pressed and then use it?

  .state('404', {
    url: '/404',
    templateUrl: '404.tmpl.html',
    controller: function ($scope, $state, APP) {
        $scope.app = APP;

        $scope.goHome = function () {
            $state.go('default.page');
        };
    }
})

$urlRouterProvider.otherwise('/404');

....

 $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {

    //fromState.name = '' on refresh
});

Thanks in advance!

8
  • how do you load the states into ui-router based on user's role? Commented Dec 14, 2015 at 8:05
  • Seems like normal behaviour since an F5 will trigger the NG-APP to be bootstrapped again. Thus your objects/states are gone. If you want to preserve them you can store them in a session. Commented Dec 14, 2015 at 8:06
  • @Amir yes, it is loaded based on a $http.get request. Commented Dec 14, 2015 at 8:08
  • When do you add that 404 state then? after you got the $http.get result? Commented Dec 14, 2015 at 8:10
  • 1
    There is a native solution to dynamic state configuration and F5 issue - stackoverflow.com/a/29013914/1679310 Commented Dec 14, 2015 at 12:57

1 Answer 1

0

The below seems to work, not sure if this is the best approach. On before unload event save the state, then use it in $stateChangeStart.

.run(function ($rootScope, $window, $state, authService, $http, $timeout, localStorageService) {

  $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {

    if (authService.isLoggedIn()) {
        if (toState.name === "404" && fromState.name === '' && localStorageService.get("LAST_STATE") !== "404") {               
            authService.loadStates($stateProviderRef).then(function () {
                $state.go(localStorageService.get("LAST_STATE"), localStorageService.get("LAST_STATE_PARAMS"));
            });                
        }           
    }

  });

  window.onbeforeunload = function () {
    localStorageService.set("LAST_STATE", $state.current.name);
    localStorageService.set("LAST_STATE_PARAMS", $state.params);
    return null;
  }

})
Sign up to request clarification or add additional context in comments.

1 Comment

as mentioned by Radim better solution using deferIntercept(defer) here stackoverflow.com/questions/24727042/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.