我有以下状态配置(简化):
$stateProvider
.state(
'showitem',
{ url: '/item/{id}', templateUrl: 'showitem.html', controller: 'MyCtrl' }
)
.state(
'notFound',
{ url: '^*path', templateUrl: '404.html'}
);
当我输入时/badurl
,显示404错误。
当我输入时/item/123
,正在查询应用程序的API以查找具有指定标识符的项目。如果找不到项目,它将返回成功的项目数据或404 HTTP标头。为了全局检测此类错误,我编写了一个http拦截器:
$httpProvider.interceptors.push(function($q, $location) {
return {
responseError: function(rejection) {
if(rejection.status == 404)
$location.path('/404');
return $q.reject(rejection);
}
};
});
代码可以工作,但是当项目的ID错误时,/item/123
URL会更改为/404
显示错误页面。
问题是-如何在不更改URL的情况下将404.html
视图加载到我的<div ui-view></div>
元素中?
有一个类似的问题,但是templateProvider似乎无法解决我的问题。
受此答案和@RadimKohler评论启发的解决方案。url
从notFound
路线中删除:
$stateProvider
.state(
'showitem',
{ url: '/item/{id}', templateUrl: 'showitem.html', controller: 'MyCtrl' }
)
.state(
'notFound',
{ templateUrl: '404.html'}
);
配置oterwise
规则:
$urlRouterProvider.otherwise(function($injector, $location) {
var $state = $injector.get('$state');
$state.go('notFound');
return $location.path();
});
最后,转到notFound
404 API错误路线:
$httpProvider.interceptors.push(function($q, $injector) {
return {
responseError: function(rejection) {
if(rejection.status == 404)
$injector.get('$state').go('notFound');
return $q.reject(rejection);
}
};
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句