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!

Baga
  • 1,354
  • 13
  • 24

1 Answers1

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;
  }

})
Baga
  • 1,354
  • 13
  • 24
  • as mentioned by Radim better solution using deferIntercept(defer) here http://stackoverflow.com/questions/24727042/angularjs-ui-router-how-to-configure-dynamic-views/29013914#29013914 – Baga Dec 14 '15 at 17:17