2015-12-14 133 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