【发布时间】:2018-01-13 08:51:07
【问题描述】:
在进行 http get 请求期间(页面完全加载之前)的单页 angular 应用程序中,如果我重新加载页面,则会调用所有 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:我真的很感动。请帮我解决它。以上是我为重现该问题而提出的一个简约问题。 我一直在开发的实际 Web 应用程序:https://codemachin.github.io/gameofthrones/
【问题讨论】:
-
谨慎使用警报和其他模式对话框,因为它们具有破坏性。他们的突然出现迫使用户停止他们当前的任务并专注于对话内容。有时这是一件好事,但大多数时候这是不必要的,而且通常很烦人。考虑其他替代方法,例如内联扩展和 toast。
-
我仍在寻找更好的解决方案,它甚至可以显示单个警报,因为重新加载是故意的。 最简单的解决方案是删除警报。发生了什么错误,为什么需要中断用户?
-
这是一个错误,我后来更正了它。我实际上的意思是 ---我仍在寻找更好的解决方案,该解决方案不甚至不会显示单个警报,因为重新加载是有意的
-
该网站已经托管在github上,我也给出了链接。也拿我的 git 存储库链接。这里是github.com/codemachin/gameofthrones
-
当询问由您的代码引起的问题时,如果您在问题本身中提供人们可以用来重现问题的代码,您将获得更好的答案。代码应该是…… Minimal - 使用尽可能少的代码,但仍然会产生同样的问题。见How to create a Minimal, Complete, and Verifiable example。
标签: javascript angularjs refresh angular-promise angular-http