我有一個簡單的角度應用程序,它有兩個使用ngRoute加載的視圖。當用戶在視圖之間導航並且用戶離開頁面時(刷新窗口,關閉選項卡或關閉瀏覽器),我需要在服務器上進行一些清理。如何發送在AngularJS中未被加載的HTTP請求?
我的第一站是這裏:Showing alert in angularjs when user leaves a page。它解決了用戶在視圖之間導航的第一種情況。我已經處理了這樣的清理:
$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();
}
});
但是,我一直無法處理用戶離開頁面的情況。按照上面的答案,這個谷歌網上論壇帖子: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(沒有服務),但也沒有工作。此時我卡住了。任何建議/線索將非常感激。
在此先感謝!
如果用戶現在離開,只需在onbeforeunload處理程序中返回一個字符串,就可以顯示數據將丟失的信息。 – Sebastian