Lev*_*zov 9 javascript onbeforeunload http-request angularjs
我有一个简单的角度应用程序,有两个使用ngRoute加载的视图.当用户在视图之间导航以及用户离开页面时(刷新窗口,关闭选项卡或关闭浏览器),我需要在服务器上进行一些清理.
我的第一站就在这里:当用户离开页面时在angularjs中显示警报.它解决了用户在视图之间导航的第一种情况.我已经像这样处理了清理工作:
$scope.$on('$locationChangeStart', function (event) {
var answer = confirm("Are you sure you want to leave this page?")
if (answer) {
api.unlock($scope.id); //api is a service that I wrote. It uses angular $http service to handle communications and works in all other cases.
} else {
event.preventDefault();
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法处理用户离开页面的情况.按照上述答案和此Google网上论坛帖子:https://groups.google.com/forum/#!topic / angular/-PfujIEdeCY我试过这个:
window.onbeforeunload = function (event) {
api.unlock($scope.id); //I don't necessarily need a confirmation dialogue, although that would be helpful.
};
Run Code Online (Sandbox Code Playgroud)
但它没有用.然后我在这里读到: 如何在onbeforeunload上执行ajax函数?请求需要同步,这里:如何$ http与AngularJS同步调用,Angular不支持这个(虽然这可能已经过时).
我也试过直接调用$ http(没有服务),但这也不起作用.此时我被困住了.任何建议/线索将非常感激.
提前致谢!
Jos*_*Ch. 15
问题是angular总是使用$ http服务进行ASYNCHRONOUS调用(并且你无法改变这种行为).由于页面在$ http服务有机会发出请求之前退出,因此无法获得所需的结果.
如果您想要一个不使用任何第三方库的workarround,请尝试以下代码:
var onBeforeUnload = function () {
var data = angular.toJson($scope.id...);//make sure you $scope is legal here...
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "apiURL/unlock", false);//the false is for making the call synchronous
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Authorization", token);
xmlhttp.send(data);
}
Run Code Online (Sandbox Code Playgroud)
它将阻止UI直到请求完成,因此尝试使服务器快速或用户会注意到.
小智 8
解决方案是在回调中$rootScope.$digest();解锁您的呼叫后进行呼叫.原因是angular的方法将配置包装在一个立即解决的promise中,这意味着ajax请求实际上不会被触发直到下一个tick.其他浏览器似乎允许在滴答之后再打勾,但不是IE11(我测试的IE的唯一版本).强制摘要周期避免了等到下一个滴答的需要.$httponbeforeunload$httponbeforeunload
| 归档时间: |
|
| 查看次数: |
11139 次 |
| 最近记录: |