角度 ui-router 中的 404 页面 [英] 404 page in angular ui-router

查看:36
本文介绍了角度 ui-router 中的 404 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在有角度的单页应用程序中使用 ui-router.我定义了一些路由,并且我有一个特定的 404 路由,如下所示:

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

注意 404 状态的 url 是 '*path',这意味着它将匹配任何路径.我这样做了,如果用户输入类似/some-non-existent-url"的内容,他不会被重定向到/404",而是停留在/some-non-existent-url",但请参阅404.html 模板.问题来了:假设我的应用程序与我的 ExampleController 中的某些 REST API 交互,并且该 API 可能会返回一个对象,或者它可能会根据 id 返回 404 Not Found从它收到的网址.因此,在我的控制器中,每当发生这种情况时,我都会尝试重定向到 404:

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

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

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?

推荐答案

对我有用的是删除 $urlProvider.otherwise('404') 并将 404 状态作为最后一个状态

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

这篇关于角度 ui-router 中的 404 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆