How to send an HTTP request onbeforeunload in AngularJS?

笑着哭i 提交于 2019-11-28 12:08:24

The problem is that angular always make ASYNCHRONOUS calls with the $http service (and you can’t change that behavior). Since the page exits before the $http service have a chance to emit the requests you are not getting the desired result.

If you want a workarround without using any third party libraries try the following code:

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

It will block UI until the request is completed, so try to make the server fast or the user will notice.

Solution is to call $rootScope.$digest(); after firing your $http calls in your onbeforeunload callback. The reason is that angular's $http methods wrap the config in an immediately resolved promise which means the ajax request doesn't actually get fired until the next tick. Other browsers appear to allow one more tick after the onbeforeunload tick, but not IE11 (the only version of IE in which I tested). Forcing the digest cycle avoids the need to wait until the next tick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!