[英]Handling 404 in resolve with angular-ui-router
I have a service with a method: 我有一种方法的服务:
service.getVenueBySlug = function(slug) {
return $http.get(API + '/venue/' + slug);
};
In my app.routes.js`: 在我的app.routes.js`中:
.state('app.venue', {
url: '/venues/:venueSlug',
templateUrl: '/app/views/venue.html',
controller: 'VenueController',
resolve: {
venue: ['VenueService', '$stateParams', '$state', function (VenueService, $stateParams, $state) {
return VenueService.getVenueBySlug($stateParams.venueSlug).then(function(res) {
return res.data;
}).catch(function(err) {
$state.go('app.404');
});
}]
}
})
The controller VenueController
simply has: 控制器VenueController
仅具有:
$scope.venue = venue
Everything is working and it's correctly redirecting to 404 if I manually go to an URL with a wrong venue slug. 一切正常,如果我手动输入带有错误的站点标记的URL,它将正确重定向到404。
The issue is that I'm receiving an error in the console that it's bothering me: 问题是我在控制台中收到一个困扰我的错误:
Does anyone know how to fix? 有谁知道如何解决? I'm using angular 1.6.4 and angular-ui-router 1.0.6. 我正在使用angular 1.6.4和angular-ui-router 1.0.6。
As mentioned in a comment to your post - in your resolve's catch, you probably should do something in the lines of: return $q.reject({redirectTo: app.404}); 如对您的帖子的评论中所述-在解决问题的过程中,您可能应该执行以下操作:return $ q.reject({redirectTo:app.404});
Then in your router config you listen to stateChangeErrors: 然后在路由器配置中,您将监听stateChangeErrors:
$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams, error) {
if(error.redirectTo) {
$state.go(error.redirectTo);
}
}
})
the $q.reject is required to handle (interrupt) the current stateChange, and the stateChangeError is there to handle that reject. $ q.reject是处理(中断)当前stateChange所必需的,而stateChangeError则在那里处理该拒绝。
(haven't tested the code but I remember having a similar solution in one of my projects) (尚未测试代码,但我记得在我的一个项目中有类似的解决方案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.