角度ui路由器中的404页 [英] 404 page in angular ui-router

查看:91
本文介绍了角度ui路由器中的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 Not Found从它收到的URL。因此,在控制器内部,只要发生这种情况,我都会尝试重定向到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'状态没有指定真实的网址:例如,如果我将其网址从'* path'更改为'/ 404',则可以正常工作,但我不想这样做,因为用户将看不到哪个是导致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?

推荐答案

您的代码有误。您正在编写 $ urlProvider.otherwise(’404’)。将其更改为 $ urlRouterProvider.otherwise(’404’)
应该可以正常工作。

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

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

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