AngularJS在解析路由器内部内容时的错误处理?
我一直在研究如何最好地处理错误。假设我有这个AngularjS代码: $routeProviderAngularJS在解析路由器内部内容时的错误处理?,angularjs,routing,Angularjs,Routing,我一直在研究如何最好地处理错误。假设我有这个AngularjS代码: $routeProvider .when('/videomail/:key', { templateUrl : 'view.html', controller : 'ViewCtrl', title : 'View', hideHeader : true, hideFooter : true, resolve: { videomail: func
.when('/videomail/:key', {
templateUrl : 'view.html',
controller : 'ViewCtrl',
title : 'View',
hideHeader : true,
hideFooter : true,
resolve: {
videomail: function($rootScope, $route, Videomail) {
return Videomail.get({key: $route.current.params.key}).$promise.then(function(videomail) {
return videomail
}, function(err) {
// How can I present the error here?
// Should I return it like 'return err' and let the controller deal with it?
// Or can I forward this to another controller?
// PS: It can be a 404 or a 401 error
})
}
}
})
查看评论中的问题。欢迎提供任何线索和提示 您可以使用
$location
服务重定向到其他路由
return Videomail.get({key: $route.current.params.key}).$promise.then(function(videomail) {
return videomail
}, function(err) {
$location.path('/error')
})
由于您不希望更改路由,也不希望处理控制器中的错误,因此可以执行以下操作:
- 用明显错误的东西来解决承诺。您必须解决该承诺,因为如果您不这样做,则根本不会加载路由,并且您无法在
中更改该承诺$routeChangeError
videomail: function($rootScope, $route, Videomail) { return Videomail.get({key: $route.current.params.key}).$promise.then(function(videomail) { return videomail }, function(err) { return { resolveError: err } }) }
- 在应用程序中的某个地方(可能在
),截取运行
,并检查是否发生错误$routeChangeSuccess
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) { if (current.locals.videomail && current.locals.videomail.resolveError) { current.locals.$template = $templateCache.get('error.html') $rootScope.error = current.locals.videomail.resolveError } } )
error.html
的模板,它将根据作用域中存在的error
对象显示一些内容
这是可行的,但我认为这是一种黑客行为。我不认为Angular应该这样使用。一般来说,您是想在所有应用程序错误处理中使用Angular,还是只在这条路线上使用Angular?谢谢,好主意。但是如何将err对象传递到新的错误页面?或者我应该改为使用$routeChangeError事件吗?您可以使用
$location.search
在URL中传递错误成员$routeChangeError
是另一种可能性,如果您想在应用程序范围内处理错误。我刚刚播放了$location.path()并不是我想要的。因为它是重定向,所以URL会改变。但我希望URL保持不变。因此我假设$routeChangeError是我的解决方案,但我还没有弄清楚如何在$routeChangeError事件处理程序中设置模板?据我所知,您无法做到这一点。如果承诺被拒绝,则根本不会加载路由的控制器和视图。你唯一能做的就是重定向。