角UI路由器处理404
我有一个包装我的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路由器状态之间的过渡:
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: {
...
}
});
我是从使用正常Angualr路由器移动和我有困难,了解如何实现404。我可以看到 ConcernService
投掷的console.log
地位拒绝,但我要如何抓住这个在国家路由器?
I'm moving from using the normal Angualr 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?
任何帮助非常AP preciated。
Any help much appreciated.
的否则()
规则仅调用时没有其他的路线的匹配。你真正需要的是拦截 $ 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
本身是建立在承诺(其中解析
解析),你的 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);
}
}