2017-02-14 33 views
0

如果用户类型myURL/myURL /#/甚至myURL /#/富他们到我的索引页。实施角UI路由器“否则”状态

但是,如果他们输入myURL/foo,他们会得到404。这太可怕了。他们应该被重定向到/

我想实现这一点,并没有很多运气。

(function() { 
    'use strict'; 

    angular 
     .module('myApp') 
     .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { 


      $stateProvider 
       .state('index', { 
        name: 'index', 
        url: '/', 
        templateUrl: 'js/views/page1.html', 
        controllerAs: 'page1Controller', 
        data: { pageTitle: 'Main' } 
       }) 
       .state('page2', { 
        name:'page2', 
        url: '/page2/:id', 
        templateUrl: 'js/views/page2.html', 
        controllerAs: 'page2Controller', 
        data: { pageTitle: 'page2' } 
       }) 
      $urlRouterProvider.otherwise('/'); 
     }]); 
})(); 

我看了几十篇文章,而且我看不到任何地方能找到这个简单的案例。

回答

0

official docs上提到你可以通过$injector$location否则函数。

他们的例子是这样的:

app.config(function($urlRouterProvider){ 
    // if the path doesn't match any of the urls you configured 
    // otherwise will take care of routing the user to the specified url 
    $urlRouterProvider.otherwise('/index'); 

    // Example of using function rule as param 
    $urlRouterProvider.otherwise(function($injector, $location){ 
     ... some advanced code... 
    }); 
}) 

你能做些什么来实现你的目标是创建一个状态,只要东西它不匹配,否则进入FCT,将其发送到该状态。

$urlRouterProvider.otherwise(function($injector, $location){ 
    $injector.get('$state').go('404'); 
}); 

我没有测试过,但应该工作。

+0

我试图做的不是网站的标准行为?任何时候用户输入一个错误的网址,他们只会回到主页上? – DaveC426913

+0

默认情况下,AngularJS将使用标签路由URL。无论在hashtag之后不是默认角度1 $ locationProvider中的有效路线。这个问题可以通过删除#(修改$ locationProvider来解决,它在Angular 2中被删除了,我希望这会有所帮助。如果你需要帮助删除#让我知道。 – flashjpr