我一直在研究如何最好地处理错误。让我们假设我有这个 AngularjS 代码:
$routeProvider
.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
})
}
}
})
查看评论中的问题。任何线索,提示都非常受欢迎!!
最佳答案
由于您不想更改路由,并且不想在 Controller 中处理错误,您可以这样做:
$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 }
})
}
run
中),拦截 $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
显示一些内容存在于范围内的对象。DEMO
它有效,但我认为这是一种黑客攻击。我不相信 Angular 应该这样使用。
关于解析路由器内部的东西时,AngularJS 错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25421400/