在我的 Angular
应用程序中,我通过 ui-router
处理路由/状态。如果一切正常——那就太好了。但是,处理 resolve
函数内部发生的错误的好方法是什么?
我目前的解决方案:
我有一个专用的 error
状态(类似于常见的 404.html
)。看起来像这样:
// inside config()
.state('error', {
url: '/error',
controller: 'ErrorCtrl',
templateUrl: 'error.html' // displays an error message
})
如果在 resolve
中发生错误,我会通过 m run
函数中广播的 $stateChangeError
捕获它:
angular.module('myModule').run(function($state) {
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
event.preventDefault();
$state.go('error');
});
});
这有效,但是我想根据错误更改我的'error.html'
中的错误消息。我不想污染 $rootScope
,我想以 ui-router
'esk 方式进行。
我当前的解决方案使用 $stateParams
将错误数据发送到我的 error
状态,但我必须为此使用 JSONified 查询参数并获得一个非常难看的 URL:
// inside config()
.state('error', {
url: '/error?data&status&config', // accept these three params
controller: 'ErrorCtrl',
templateUrl: 'error.html' // displays an error message
})
angular.module('myModule').run(function($state) {
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
event.preventDefault();
$state.go('error', JSON.stringify(error)); // error has data, status and config properties
});
});
问题
有没有不同的方法可以将 error
对象传递到我的 error
状态而不会使我的 URL 变丑? (注意:我的 error
对象很复杂,而不仅仅是一个简单的字符串。)
最佳答案
一个对我有用的策略是让 resolve
函数返回一个带有错误对象的被拒绝的 promise :
$stateProvider.state('needs_authentication', {
url: '/auth',
resolve: {
user: function ($q, authService) {
if (authService.isAuthenticated()) {
...
}
else {
var errorObject = { code: 'NOT_AUTHENTICATED' };
return $q.reject(errorObject);
}
}
}
});
这让您的 $stateChangeError
函数能够处理特定的错误情况:
$rootScope.$on('$stateChangeError', function (evt, toState, toParams, fromState, fromParams, error) {
if (angular.isObject(error) && angular.isString(error.code)) {
switch (error.code) {
case 'NOT_AUTHENTICATED':
// go to the login page
$state.go('login');
break;
default:
// set the error object on the error state and go there
$state.get('error').error = error;
$state.go('error');
}
}
else {
// unexpected error
$state.go('error');
}
});
关于javascript - 处理ui-routers解析功能中的错误? (又名 $stateChangeError)将数据传递到错误状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936865/