angularjs – Angular UI路由器刷新时的动态状态变为404

前端之家收集整理的这篇文章主要介绍了angularjs – Angular UI路由器刷新时的动态状态变为404前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在根据当前用户角色动态加载状态.但是当刷新页面时,它将转到404页面.另外在$stateChangeStart事件中,fromState.name为空.

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

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

提前致谢!

解决方法

以下似乎有效,不确定这是否是最佳方法.在卸载事件之前保存状态,然后在$stateChangeStart中使用它.

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

  $rootScope.$on('$stateChangeStart',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;
  }

})

猜你在找的Angularjs相关文章