javascript - 如何在 AngularJS 中发送 HTTP 请求 onbeforeunload?

标签 javascript angularjs onbeforeunload http-request

我有一个简单的 Angular 应用程序,它有两个使用 ngRoute 加载的 View 。当用户在 View 之间导航以及当用户离开页面(刷新窗口、关闭选项卡或关闭浏览器)时,我需要在服务器上做一些清理工作。

我的第一站在这里:Showing alert in angularjs when user leaves a page .它解决了用户在 View 之间导航的第一种情况。我已经像这样处理了清理工作:

$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();
    }
});

但是,我无法处理用户离开页面的情况。按照上述答案和此 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. 
};

但是没有用。然后我在这里阅读:How to execute ajax function onbeforeunload?请求需要同步,这里:How to $http Synchronous call with AngularJS Angular 不支持这个(尽管这个可能已经过时了)。

我也试过直接调用 $http(没有服务),但也没有用。在这一点上我被卡住了。任何建议/线索将不胜感激。

提前致谢!

最佳答案

问题是 Angular 总是使用 $http 服务进行异步调用(你无法改变这种行为)。由于页面在 $http 服务有机会发出请求之前退出,因此您没有得到想要的结果。

如果你想在不使用任何第三方库的情况下尝试以下代码:

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);
}

它会阻塞 UI 直到请求完成,所以尽量让服务器快点,否则用户会注意到。

关于javascript - 如何在 AngularJS 中发送 HTTP 请求 onbeforeunload?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689233/

相关文章:

javascript - 避免 mouseover mouseleave 冲突

javascript - 如何在执行 ng repeat 时生成具有默认值的数组属性?

javascript - 为数组中的每个对象添加属性

javascript - beforeunload 或 onbeforeunload

javascript检测用户是否离开了网站或只是刷新/点击了链接

javascript - 取消转义 html 字符实体

javascript - 使用 ui-router 时谷歌地图不显示

javascript - 如何在 js 数组中复制元素而不创建 "dependent elements"?

javascript - 为什么此 SVG 中的渐变显示为黑色?

javascript - 在 window.onbeforeunload 中换行?