2015-12-14 134 views
4

我基于当前用户角色动态加载状态。但是当页面刷新时,它会进入404页面。同样在$ stateChangeStart事件fromState.name是空的。刷新的角度UI路由器动态状态转至404

有没有办法进入刷新按钮被点击之前的状态?我应该在按下刷新之前存储状态,然后使用它?

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

提前感谢!

+0

如何根据用户角色将状态加载到ui-router? –

+0

看起来像正常行为,因为F5会触发NG-APP再次启动。因此你的对象/状态消失了。如果你想保存它们,你可以将它们存储在一个会话中。 – skubski

+0

@Amir是的,它是基于$ http.get请求加载的。 – Baga

回答

0

以下似乎工作,不知道这是否是最好的方法。在卸载事件之前保存状态,然后在$ 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; 
    } 

}) 
+0

由Radim更好的解决方案使用deferIntercept(延迟)在这里提到http://stackoverflow.com/questions/24727042/angularjs-ui-router-how-以进行配置,动态视图/ 29013914#29013914 – Baga