我在有 Angular 的单页应用程序中使用 ui-router。我定义了一些路由,并且有一个特定的 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 是“*path”,这意味着它将匹配任何路径。我这样做是为了如果用户输入类似“/some-non-existent-url”的内容,他不会被重定向到“/404”,而是停留在“/some-non-existent-url”,但请参阅404.html 模板。问题来了:假设我的应用程序与 ExampleController 内的某些 REST API 进行交互,并且该 API 可能会返回一个对象,或者可能会根据 id 返回 404 Not Found从它收到的网址。因此,在我的 Controller 内,每当发生这种情况时,我都会尝试重定向到 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 响应的真实 URL。有没有办法解决这个问题?
最佳答案
您的代码有错误。您正在编写 $urlProvider.otherwise('404')
。将其更改为 $urlRouterProvider.otherwise('404')
。
这应该可以让它工作。
关于angularjs - Angular ui 路由器中的 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41753156/