在正在进行的http get请求期间(页面完全加载之前)的单页角度App中,如果我重新加载页面,则会调用所有http请求错误回调。我使用谷歌浏览器。 将以下代码保存在html文件中,并在页面打开后重新加载页面以重现问题。 这会打破整个页面,因为它会显示来自所有被调用API的警报。 如果有50个待处理的http请求,我在http请求期间重新加载页面时会收到50错误警告。我不想从http get的errorCallBack函数中删除警报。如果我在完成所有ajax http请求后重新加载页面,那么它不会显示任何错误。 请帮我解决这个问题。
<div ng-app="iceApp" ng-controller="allCharacterController as myCharacter">
<input type="text" id="search1" ng-model="search.name">
<div ng-repeat="book in myCharacter.character | filter : search">
{{book.name}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('iceApp', []);
myApp.controller('allCharacterController',['$http',function($http) {
var main = this;
this.character=[];
this.baseUrl = 'https://www.anapioficeandfire.com/api/';
// there were 50 pages to get data from thats why i have made a loop
this.allCharacters = function(){
for(i=1;i<50;i++){
$http({
method: 'GET',
url: main.baseUrl+"characters?page="+i+"&pageSize=50"
})
.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(response.data);
if(response.data.length>0){
main.character.push.apply(main.character,response.data);
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("some error occurred. Check the console.");
console.log(response);
});
}
}// end load all blogs
this.allCharacters();
}])
</script>
ps:我真的很震惊。请帮我解决一下。以上是我为重现问题所做的简约问题。
我一直致力于实际的网络应用程序:https://codemachin.github.io/gameofthrones/
答案 0 :(得分:0)
BookService.getAllHouses([i])
.then(function successCallback(response) {
if(response.data.length>0){
main.all.push.apply(main.all,response.data);
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("some error occurred. Check the console.");
console.log(response);
//IMPORTANT
throw response;
});
当.catch
处理程序无法重新抛出错误时,将拒绝的承诺转换为成功的承诺。
一种方法是减少警报的数量,使用$q.all来提供单个拒绝处理程序。
this.allHouses = function(){
var promiseList = [];
for(let i=1;i<12;i++){
var promise = BookService.getAllHouses([i])
.then(function onSuccess(response) {
if(response.data.length>0){
main.all.push.apply(main.all,response.data);
}
return response.data;
});
promiseList.push(promise)
};
return $q.all(promiseList)
.catch( function onRejection(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("some error occurred. Check the console.");
console.log(response);
throw response;
});
}
使用$q.all,如果任何承诺以拒绝方式结算,则所产生的承诺将被拒绝,并带有第一个拒绝承诺的拒绝价值。
此示例通过返回可用于进一步链接的promise来改进allHouses
函数。