404 page in angular ui-router

微笑、不失礼 提交于 2019-12-11 06:08:48

问题


I am using ui-router in an angular single page application. I have some routes defined, and I have a specific 404 route like this:

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'
      })
})

Notice how the url for 404 state is '*path', which means it will match any path. I made it so if the user types something like '/some-non-existent-url' he won't be redirected to '/404', but rather stay at '/some-non-existent-url', but see the 404.html template. Here comes the problem: say my app interacts with some REST API inside my ExampleController, and the API may return an object, or it may return 404 Not Found based on the id from the url it receives. So, inside my controller, whenever this happens, I try to redirect to 404:

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

This is where the weird staff occurs. It displays the 404.html template - for a split second - and then redirects to home page (did not include it in my code here for the sake of brevity). My guess is that the '404' state does not have a real url specified: if I change it's url from '*path' to '/404' for example, this works fine, but I don't want to do this, as the user won't see which was the real url that caused a 404 response. Is there any workaround for this problem?


回答1:


You have a mistake in your code. You are writing $urlProvider.otherwise('404'). Change it to $urlRouterProvider.otherwise('404'). That should get it working.




回答2:


What worked for me was to remove $urlProvider.otherwise('404') and have the 404 state as the last state



来源:https://stackoverflow.com/questions/41753156/404-page-in-angular-ui-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!