Anthony D
Anthony D

Reputation: 123

Browser reload doesn't reload current Angular view

The problem I'm having is that after a user logs-in or signs-up they are redirected to the games view, this happens within the createUser function or after a successful authentication; in either case the redirect is handled with $state.go('games').

This all works fine, however, if the user navigates away from the games view to any other state like createGame or dashBoard and then refreshes the browser in one of those views they are always redirected back to the games view. When I remove the $state.go('games') this doesn't happen, and reload will only reload the current view (like it should).

I have tried changing parameters on $state.go and tried using $state.transitionTo(), but nothing changes this behavior.

Is this just normal behavior for $state.go? If not, am I using it wrong, and are there other ways to redirect? What can I do to stop this behavior?

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

Upvotes: 0

Views: 579

Answers (1)

ddelemeny
ddelemeny

Reputation: 1931

It's not about $state.go

It's actually about when you call it, $state.go does one simple thing : trigger a change in the routing state off your application. You just happen to do it everytime your application authenticates your user against your $firebaseAuth service, in the $onAuth handler.

A single page app is an app

When you refresh the page in the browser, the entire app reloads, starts again, boostraps everything to display your app. This startup process includes re-authenticating your user (I didn't quite see where it is done in your code, but it has to be done), thus triggering the $onAuth handler again… and ultimately execute $state.go('games') again.

Put your $state.go invocation elsewhere

You don't actually mean to do it every time your app authenticates the user, you rather want to do it when your user performs a successful login or sign-up action. $authWithPassword returns a promise, you could do the state change in a success callback when the promise is resolved.

Hope that helps !

Upvotes: 1

Related Questions