404 page in angular ui-router

2019-07-28 12:03发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-07-28 12:37

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

查看更多
成全新的幸福
3楼-- · 2019-07-28 12:43

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

查看更多
登录 后发表回答