2017-01-19 183 views
1

我在角度单页面应用程序中使用ui路由器。我也定义了一些路线,我有这样一个特定的404路线:在角度ui路由器404页面

app.config(function($urlRouterProvider, $stateProvider){ 
    $urlProvider.otherwise('404') 
    $stateProvider 
     .state('example', { 
     url: '/example/:id', 
     templateUrl: 'example.html', 
     controller: 'ExampleController' 
     })  
     .state('404', { 
     url: '*path', 
     templateUrl: '404.html' 
     }) 
}) 

通告404状态下的URL是如何“*路径”,这意味着它将匹配任何路径。我做到了这一点,如果用户输入类似'/ some-non-existent-url'的东西,他不会被重定向到'/ 404',而是停留在'/ some-non-existent-url',但看到404.html模板。问题来了:假设我的应用程序与我的示例控制器中的一些REST API交互,并且API可能会返回一个对象,或者它可能会返回404 Not Found,它基于它接收的url中的id。所以,我的控制器中,每当出现这种情况,我尝试重定向到404:

app.controller('ExampleController', function($state){ 
    someAPICall().then(function(response){ // do something}, 
         function(response){ 
          if(response.status == 404){ 
           $state.go('404'); 
          } 
         }); 
}); 

这是怪异的员工发生。它显示了404.html模板 - 一秒钟 - 然后重定向到主页(为了简洁起见,没有在我的代码中包含它)。我的猜测是,'404'状态没有指定真正的URL:如果我将它的URL从'* path'更改为'/ 404',例如,这工作正常,但我不想这样做,因为用户将不会看到哪个是导致404响应的真实URL。有没有解决这个问题的方法?

+0

我想在这里做一个例子https://jsfiddle.net/ojzdxpt1/10/对我来说,它看起来像最后的状态它正在工作,但不知道你是如何在一起做这件事,这是很难知道的。您可能在stateProvider中有一些我不知道的冲突状态 – Ronnie

回答

0

您的代码有误。您正在编写$urlProvider.otherwise('404')。将其更改为$urlRouterProvider.otherwise('404')。 这应该让它工作。

0

什么工作对我来说是去除$urlProvider.otherwise('404'),并有404状态