AngularJS UI路由器处理404 [英] AngularJS UI router handling 404s
问题描述
我有一个带有服务的应用程序,该服务包装了我的API调用:
I have an app with a service which wraps my API calls:
var ConcernService = {
...
get: function (items_url, objId) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url + objId}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
console.log('ConcernService.get status',status);
defer.reject(status);
});
return defer.promise;
},
我正在使用UI-Router在状态之间进行转换:
and I'm using UI-Router to transition between states:
concernsApp
.config( function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404/");
$stateProvider.state('project', {
url: '/project/:projectId/',
resolve: {
project: function ($stateParams, ConcernService) {
return ConcernService.get('projects/', $stateParams.projectId);
},
},
views: {
...
}
});
我不再使用普通的AngularJS路由器,并且难以理解如何实现404.我可以看到ConcernService
抛出console.log
状态被拒绝,但是如何在状态路由器中捕获它呢?
I'm moving from using the normal AngularJS router and I'm having difficulty understanding how to implement 404s. I can see the ConcernService
throwing the console.log
status as rejected, but how do I catch this in the state router?
推荐答案
仅当没有其他 route 匹配时,才调用otherwise()
规则.您真正想要的是拦截$stateChangeError
事件,该事件是在状态转换中发生问题(例如,解析失败)时触发的.您可以在状态更改事件文档中了解有关此内容的更多信息.
The otherwise()
rule is only invoked when no other route matches. What you really want is to intercept the $stateChangeError
event, which is what gets fired when something goes wrong in a state transition (for example, a resolve failing). You can read more about that in the state change event docs.
您要执行的操作的最简单实现是这样的:
The simplest implementation for what you're trying to do would be something like this:
$rootScope.$on('$stateChangeError', function(event) {
$state.go('404');
});
此外,由于$http
本身是基于promise(resolve
可以解决的)构建的,因此您的ConcernService
方法可以简化为单一格式(我意识到您将其扩展用于调试目的,但是您可以就像链接一样简单,仅供参考):
Also, since $http
itself is built on promises (which resolve
resolves), your ConcernService
method can be simplified down to a one-liner (I realize you expanded it for debugging purposes, but you could have just as easily chained it, just FYI):
var ConcernService = {
get: function (items_url, objId) {
return $http.get(api_url + items_url + objId);
}
}
这篇关于AngularJS UI路由器处理404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!