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

标签 angularjs angular-ui-router

我正在根据当前用户 Angular 色动态加载状态。但是当页面刷新时,它会转到 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, $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;
  }

})

关于angularjs - 刷新时的 Angular UI 路由器动态状态变为 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34262131/

相关文章:

javascript - 在 $stateProvider 中动态注入(inject)值

angular - 为什么 Angular 在自定义 ControlValueAccessor 组件上调用 `registerOnChange` 之后调用 `ngOnDestroy`?

angularjs - Ui-Router $state.go inside $on ('$stateChangeStart' )正在导致无限循环

javascript - 如何将对象推送到数组数组中

angularjs - 按值数组进行 Angular 过滤

angularjs - ui-router url 中的查询字符串参数?

angularjs - 为什么 $state.transitionTo 或 $state.go 不显示新的 HTML 部分?

javascript - 遍历 Javascript 对象并计数

javascript - 如何在 AngularJS Emit 中将函数作为参数传递?

javascript - Angular 将文件另存为 csv 导致失败 - 网络错误仅在 Chrome 上