$scope.roomName = $route.current.pathParams.roomName;
$scope.users = [];
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room',
data: {
name: $route.current.pathParams.roomName
},
responseType: 'json'
}).then(function(response) {
responseData = response.data[0];
if(!responseData.room) {
backToMenu();
}
$scope.room = responseData.room;
$scope.status = responseData.room.status;
$scope.usersCount = responseData.room.users.length;
$scope.owner = responseData.room.userName;
if(responseData.room.users.length < 2)
addUser();
else {
backToMenu();
}
}, function(response) {
backToMenu();
});
function backToMenu() {
$location.path('/');
}
$scope.backToMenu = function() {
backToMenu();
};
$scope.$on('$locationChangeStart', function (event, next, current) {
if(current != next) {
var answer = confirm("Opuszczająć tą stronę zostaniesz usunięty w pokoju!");
if( !answer ) {
event.preventDefault();
}else{
removeUser();
}
}
});
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Opuszczająć tą stronę zostaniesz usunięty w pokoju!";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
removeUser();
return confirmationMessage; //Webkit, Safari, Chrome
});
function addUser() {
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room/addUser',
data: {
userName: SessionService.get('userName'),
name: $route.current.pathParams.roomName
},
responseType: 'json'
});
}
function removeUser() {
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room/removeUser',
data: {
userName: SessionService.get('userName'),
name: $route.current.pathParams.roomName
},
responseType: 'json'
});
}
$interval(function() {
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room',
data: {
name: $route.current.pathParams.roomName
},
responseType: 'json'
}).then(function(response) {
console.log('interval');
room = response.data[0].room;
if(!room)
backToMenu();
$scope.users = room.users;
$scope.status = room.status;
$scope.usersCount = room.users.length;
$scope.room = room;
});
}, 1000);
$scope.startGame = function() {
changeStatus('granie');
};
function changeStatus(status) {
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room/changeStatus',
data: {
name: $route.current.pathParams.roomName,
status: status
},
responseType: 'json'
});
}
$scope.sendChoice = function(choice) {
$http({
method: 'POST',
url: mainConfig.serverUrl + 'room/sendChoice',
data: {
name: $route.current.pathParams.roomName,
choice: choice,
userName: SessionService.get('userName')
},
responseType: 'json'
});
}
I pasted whole code of my controller. I try to redirect my page using $location to path '/' when $http function doesn't get a room, but it doesn't work. I added click event on a button that trigger a function $scope.backToMenu and then it works fine. Also it works when I use it out of $http function with $timeout -
$timeout(function() {
$location.path('/');
}, 3000);
Any ideas what is wrong?