2014-09-19 78 views
0

我使用這個捕獲錯誤並重定向到一個錯誤頁面轉到錯誤狀態和URL保持的狀態產生

module.run(function ($state, $rootScope, translateService) { 
    $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) { 
     $state.go("app.error"); 
    }); 
}); 

錯誤,但這個移動到錯誤狀態,並改變URL 。我想轉到錯誤頁面並將URL保存到出錯頁面。

我試過使用位置選項$state.go("app.error", null, { location: false }),但它保持我來自的狀態的URL而不是錯誤的URL。

我可以以某種方式進入錯誤狀態並保留URL或進入錯誤狀態,然後將URL更改回toState的URL?

回答

3

我通過將錯誤信息發送到錯誤狀態來解決它,然後在那裏設置帶有$ location.path的url。

module.run(function ($state, $rootScope) { 
    $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) { 
     $state.get("app.error").$error = { 
      toState: toState, 
      toParams: toParams, 
      fromState: fromState, 
      fromParams: fromParams, 
      message: error.message, 
      stack: error.stack 
     }; 

     $state.go("app.error"); 
    }); 
}); 

module.config(function ($stateProvider, $urlRouterProvider) { 
    $stateProvider.state("app.error", { 
     url: "/error", 
     resolve: { 
      error: function() { 
       return this.self.$error; 
      } 
     }, 
     templateUrl: "app/error.tpl.html", 
     controller: function ($state, $scope, $log, $location, error) { 
      if (error) { 
       $location.path($state.href(error.toState, error.toParams).replace(/^#/, "")); 
       $log.error(error.message, error.stack); 
      } 

      $scope.error = error; 
     } 
    }); 
}); 
0

我覺得這個做的伎倆(我發現這招前一段時間,它不記錄):

$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) { 
    event.preventDefault(); 

    $state.go("app.error", {}, { location: false }); 
}); 

https://github.com/angular-ui/ui-router/wiki 看看約$ stateChangeError

+0

等一下對不起。這隻適用於像href或直接瀏覽器地址欄更新那樣的直接url導航。 不帶$ state.go。 – FloG 2015-06-12 12:54:25

0

到零件添加到接受的答案,我做了一個小的更改,讓我保留錯誤的url,但嘗試去用戶試圖刷新時的主頁(或任何你想要的狀態):

controller: function ($state, $scope, $log, $location, error) { 
     if (error) { 
      $log.error(error.message, error.stack); 
     }else{ 
      $state.go('app'); // or app.home or whatever 
     } 

     $scope.error = error; 
    }