gpt4 book ai didi

angularjs - 如何处理 Angular-ui-router 解析中的错误

转载 作者:行者123 更新时间:2023-12-02 21:45:26 25 4
gpt4 key购买 nike

我正在使用 Angular-ui-router 的 resolve 在移动到某个状态之前从服务器获取数据。有时对服务器的请求失败,我需要通知用户该失败。如果我从 Controller 调用服务器,我可以放置 then 并在其中调用我的通知服务,以防调用失败。我将对服务器的调用放在 resolve 中,因为我希望后代状态在启动之前等待服务器的结果。

如果调用服务器失败,我可以在哪里捕获错误? (我已阅读 documentation 但仍不确定如何阅读。另外,我正在寻找尝试这个新代码片段工具的理由:)。

"use strict";

angular.module('MyApp', ["ui.router"]).config([
"$stateProvider",
"$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/item");
$stateProvider
.state("list", {
url: "/item",
template: '<div>{{listvm}}</div>' +
'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
'<ui-view />',
controller: ["$scope", "$state", function($scope, $state){
$scope.listvm = { state: $state.current.name };
}]
})
.state("list.detail", {
url: "/{id}",
template: '<div>{{detailvm}}</div>',
resolve: {
data: ["$q", "$timeout", function ($q, $timeout) {
var deferred = $q.defer();
$timeout(function () {
//deferred.resolve("successful");
deferred.reject("fail"); // resolve fails here
}, 2000);
return deferred.promise;
}]
},
controller: ["$scope", "data", "$state", function ($scope, data, $state) {
$scope.detailvm = {
state: $state.current.name,
data: data
};
}]
});
}
]);
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>

<div ng-app="MyApp">
<ui-view />
</div>

最佳答案

老问题,但我遇到了同样的问题,并在 ui-router 的常见问题解答部分偶然发现了这个问题

If you are having issues where a trivial error wasn't being caught because it was happening within the resolve function of a state, this is actually the intended behavior of promises per the spec.

errors within resolve

因此您可以像这样捕获应用程序运行阶段的所有解析错误

$rootScope.$on('$stateChangeError', 
function(event, toState, toParams, fromState, fromParams, error){
// this is required if you want to prevent the $UrlRouter reverting the URL to the previous valid location
event.preventDefault();
...
})

关于angularjs - 如何处理 Angular-ui-router 解析中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com