Tomas
Tomas

Reputation: 1262

Resolve user data after full page reload in AngularJS

In my angular application, after full page reload happens, I want to be able to retrieve the user information via $http.get and if the user is logged in($http.get returns user info) then I want to show the 'about me' page, if user is not logged in then they should see the login page.

Currently I tried doing this in application.run method as shown in the code below, but since $http is async, the $rootScope.currentUser does not get set for some time and I get transferred to the login page by my $routeChangeStart event handler even when i'm logged in.

myAPp.config(function ($routeProvider) {
    $routeProvider.when('/', {
      templateUrl: '/app/homeView/home.html',
      controller: 'HomeViewController'
    }).when('/login', {
      templateUrl: '/app/loginView/login.html',
      controller: 'LoginController'
    }).when('/me', {
      templateUrl: '/app/userInfoView/userInfo.html',
      controller: 'UserInfoController',
      access: {
        requiresLogin: true
      }
    }).otherwise({
      redirectTo: '/'
    });
  }
);

myApp.run(function ($rootScope, $cookies, $location, UserService) {
  UserService.getCurrentUser().then(
    function (response) {
      $rootScope.currentUser = response;
    },
    function () {
      $rootScope.currentUser = null;
    }
  );

  $rootScope.$on('$routeChangeStart', function (event, next) {
    if (next.access !== undefined) {
      if (next.access.requiresLogin && !$rootScope.currentUser) {
        $location.path('/login');
      } else {
        $location.path('/me');
      }
    }
  });
});

What is the correct way to solve this problem?

Upvotes: 0

Views: 206

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Following what @FuzzyTree started the following should do what you need

myApp.run(function($rootScope, $cookies, $location, UserService) {
  var userPromise = UserService.getCurrentUser().then(
    function(response) {
      $rootScope.currentUser = response;
    },
    function() {
      $rootScope.currentUser = null;
    }
  );

  $rootScope.$on('$routeChangeStart', function(event, next) {
    if (next.access !== undefined) {
      if (next.access.requiresLogin && !$rootScope.currentUser) {
        // prevent this change
        event.preventDefault();
        // let user promise determine which way to go
        userPromise.then(function() {
          // will call another `$routeChangeStart` but 
          // that one will pass around the above conditional
          $location.path('/me');// modify using `next.url` if app gets more robust
        }).catch(function() {
          $location.path('/login');
        });

      }
    }
  });
});

Upvotes: 2

terafor
terafor

Reputation: 1626

you can:

Upvotes: 1

Related Questions