Проблема, с которой я столкнулась, заключается в том, что после входа пользователя в систему или регистрации они перенаправляются в представление игр, это происходит в функции createUser или после успешной аутентификации; в любом случае переадресация обрабатывается с помощью $state.go('games')
.Перезагрузка перезагрузки не перезагружается. Угловой вид
Это все работает отлично, однако, если пользователь переходит от игры смотреть в любое другое состояние, как createGame или DashBoard, а затем обновляет браузер в одном из тех взглядов, которые они всегда перенаправлены обратно к играм Посмотреть. Когда я удаляю $state.go('games')
, этого не происходит, и перезагрузка перезагружает текущее представление (как и должно).
Я попытался изменить параметры на $state.go
и попытался использовать $state.transitionTo()
, но ничего не изменилось.
Это просто нормальное поведение для $state.go
? Если нет, я использую его неправильно, и есть ли другие способы перенаправления? Что я могу сделать, чтобы остановить это поведение?
var game = angular.module('game', ['ui.router','firebase']);
game.config(['$stateProvider', '$locationProvider', function($stateProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider.state('signUp', {
url: '/signUp',
templateUrl: '/templates/signUp.html'
});
$stateProvider.state('games', {
url: '/games',
templateUrl: '/templates/games.html',
controller: 'games.controller'
});
$stateProvider.state('login', {
url: '/login',
templateUrl: '/templates/login.html'
});
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: '/templates/dashboard.html',
controller: 'dashboard.controller'
});
$stateProvider.state('createGame', {
url: '/createGame',
templateUrl: '/templates/createGame.html',
controller: 'createGame.controller'
});
}]);
// Root reference to database
game.factory("Fire", function($firebaseAuth) {
var ref = new Firebase("https://money-game.firebaseIO.com/");
return ref;
});
// Gives access to auth methods
game.factory("Auth", ["$firebaseAuth", "Fire",
function($firebaseAuth, fire) {
return $firebaseAuth(fire);
}
]);
game.controller('app.controller', ['$scope', '$state', '$stateParams', 'Auth', 'Fire', function ($scope, $state, $stateParams, auth, fire) {
$scope.user = {
email : '',
password : ''
};
$scope.signUp = function() {
auth.$createUser($scope.user)
.then(function(userData) {
// After successful signup save a user record to users under their auth ID
fire.child('users').child(userData.uid).set({
name : $scope.user.name,
email : $scope.user.email,
joined : Date.now()
});
$state.go('games');
console.log("User " + userData.uid + " created successfully!");
})
.catch(function(error) {
console.error("Error: ", error);
});
};
$scope.login = function() {
auth.$authWithPassword($scope.user).catch(function(error) {
console.error("Authentication failed:", error);
});
};
$scope.logout = function() {
auth.$unauth();
window.location = '/';
};
auth.$onAuth(function(authData) {
if (authData) {
$scope.activeUser = authData;
// After user logs in find user record by auth id
fire.child('users').child(authData.uid).on('value', function(snapshot) {
// Checks if user exsists
if (snapshot.exists()) {
// sets scope user to the user data
$scope.user = snapshot.val();
// sets scope user id to the auth id
$scope.user.id = snapshot.key();
}
});
console.log("Logged in as:", authData.uid);
$state.go('games');
} else {
$scope.activeUser = false;
// $scope.user = '';
}
});
}]);
game.controller('games.controller', ['$scope', '$state', '$stateParams', 'Auth', '$firebaseArray','Fire', function ($scope, $state, $stateParams, auth, $firebaseArray, fire) {
$scope.games = $firebaseArray(fire.child('games'));
$scope.view = 'listView';
$scope.setCurrentGame = function(game) {
$scope.currentGame = game;
};
$scope.addPlayer = function(game) {
console.log(game.$id);
var ref = fire.child('players').child(game.$id);
ref.push({
id : $scope.user.id,
name : $scope.user.name,
email : $scope.user.email
})
};
// swap DOM structure in games state
$scope.changeView = function(view){
$scope.view = view;
}
}]);
game.controller('createGame.controller', ['$scope', '$state', '$stateParams', 'Auth', '$firebaseArray','Fire', function ($scope, $state, $stateParams, auth, $firebaseArray, fire) {
$scope.games = $firebaseArray(fire.child('games'));
$scope.createGame = function() {
if ($scope.format == 'Match Play') {
$scope.skinAmount = 'DOES NOT APPLY';
$scope.birdieAmount = 'DOES NOT APPLY';
}
$scope.games.$add({
name: $scope.gameName,
host: $scope.user.name,
date: $scope.gameDate,
location: {
course: $scope.courseName,
address: $scope.courseAddress
},
rules: {
amount: $scope.gameAmount,
perSkin: $scope.skinAmount,
perBirdie: $scope.birdieAmount,
format: $scope.format,
holes : $scope.holes,
time: $scope.time
}
})
// $state.go('games');
};
}]);
'$ state.go()' означает перейти к состоянию, которое вы указываете. Так что это звучит так, как будто он работает нормально. Вы говорите, если вы раскомментируете '$ state.go' в контроллере, тогда он пойдет в игры? Если да, то это правильно. –
Его прокомментировал, потому что я работал над этим, извините. Перенаправление в игры работает нормально, но в любое время после этого браузер перезагружается/обновляется, он всегда возвращается к просмотру игр, а не перезагружает текущее представление. Пример: если я здесь http: // localhost: 3010/createGame, и нажмите кнопку перезагрузки, я буду здесь http: // localhost: 3010/games. Это только в случае, когда я перенаправляю с помощью $ state.go(), если я удалю его, нажатие кнопки перезагрузки в браузере перезагрузит любой вид, в котором я включен, но не всегда возвращаясь к просмотру игр. –