2014-10-03 152 views
2

在我的AngularJS應用程序,我想捕獲錯誤,並且用戶發送到404的狀態,像這樣:AngularJS UI路由器的狀態,但使用不同的URL

$rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ 
    //console.log(unfoundState.to); 
    //console.log(unfoundState.toParams); 
    //console.log(unfoundState.options); 
    $state.go('404'); 
}); 

這是當用戶點擊一個壞鏈路(例如沒有狀態下,與狀態,但沒有任何內容那些由否則方法處理)在該應用中,等

的代碼加載404狀態罰款:

.state('404', 
     { 
      views: { 
       'body': { 
        templateUrl: 'partials/404.html', 
       } 
      } 
     }); 

但我想要做的是將URL更改爲他們嘗試訪問的狀態,所以基本上加載404狀態,但使用不正確的URL(因爲404將在服務器環境中工作)。

我已經研究過這樣做的:

history.replaceState(null, null, unfoundState.to); 
$state.go('404'); 

但是,這會導致應用程序的主要錯誤,並改變URL,但不是國家!

我該怎麼做?

+1

我還沒有嘗試過。我不確定'$ state.transitionTo('404',{},{location:false});'是否有效。 – 2014-10-06 14:29:16

回答

1

試試這個來捕獲所有的網址不匹配任何以前的路線:

.state("404", { 
    url: "*path", // will catch all URLs 
    templateUrl: 'partials/404.html' 
}) 
1

按照docs,我覺得你可以這樣做:

$state.go('404',{},{location:false}); 

注:我在創建一個plunkr的過程來驗證,但我沒有時間完全完成它現在