解决中失败的异步调用 [英] Failed async call in resolve
问题描述
我在我的 app.config
中添加了以下内容,以便在允许我的任何路由开始使用其关联的控制器之前解析全局所需的变量.这一直很好,但是我担心这个异步调用掉入的场景.如果发生这种情况,将无法正确解决,并且我的应用程序将永远不会呈现.我该如何防范这种情况?
I've added the following to my app.config
in order to resolve a globally needed variable before allowing any of my routes to kick off their associated controller. This has been working great, however I am concerned about scenarios in which this async call falls. If that were to happen this would not resolve properly and my app would never render. How could I protect against this scenario?
var originalWhen = $routeProvider.when;
$routeProvider.when = function(path, route) {
if (!route.resolve) {
route.resolve = {};
}
angular.extend(route.resolve, {
availableCodes: function($rootScope, serverService) {
if ($rootScope.isAuthenticated) {
return numbersService.getAvailableCodes().$promise.then(function(data) {
$rootScope.availableCodes = data.codes;
});
}
}
});
return originalWhen.call($routeProvider, path, route);
};
推荐答案
对于全局解析程序,修补当
不是最佳解决方案时(方法修补是极端情况,应尽可能避免使用),通常将它们放入 $ routeChangeStart
侦听器会更干净,并提供更多控制权.
For global resolvers patching when
isn't the best solution (method patching is an extreme case and should be avoided if possible), generally putting them to $routeChangeStart
listener is cleaner and gives more control.
错误应在 $ routeChangeError
中处理,侦听器将拒绝原因作为第四个参数:
The errors should be handled in $routeChangeError
, listeners get rejection reason as the fourth argument:
var ignored = ['/resolver-error'];
$rootScope.$on('$routeChangeStart', function (e, to) {
if (ignored.indexOf(to.originalPath) >= 0)
return;
to.resolve = to.resolve || {};
// can be overridden by route definition
to.resolve.availableCodes = to.resolve.availableCodes || 'availableCodesService';
});
$rootScope.$on('$routeChangeError', function (e, to, from, reason) {
if (reason === ...) {
$location.path('/resolver-error');
}
});
这允许在至少一条应该提供有关分辨率错误反馈的路由上跳过此解析器.
This allows to skip this resolver on at least one route which is supposed to provide a feedback on resolution error.
这篇关于解决中失败的异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!