0

I am working on a app and try to make a login that prevents all users can access the web app. What i did is using ui.router.grant. After a user is logged in (this already works) the userValue is set and returns true or false, based on that you'll have to login or can access a page.

In the .run function grant.addTest needs the userValue and that's already works. But when I refresh the page I lose the userValue. So I have to check the loginstatus on launching or refreshing the web app.

How and where I can call the apiFactory to set the userValue before the .run function executes?

Here a part of my code:

angular.module('appName', [
    'controllers.login', 
    'userValue',
    'apiFactory',
    'ui.router.grant'
])

angular.module('userValue', [])
    .value('userValue', {
        logged_in: false
    });

.run(function(grant, userValue) {
    grant.addTest('admin', function() {
        isAdmin = userValue.logged_in;
        return isAdmin;
    });

})

angular.module('apiFactory', [])

    .factory('apiFactory', function($http) {

        // VARIABLES
        var urlBase = 'http://myappurl.com/api';
        var apiFactory = {};

        // APP LOGIN   
        apiFactory.appLogin = function (username, password) {
            return $http.post(urlBase + '/authentication/login/?username=' + username + '&password=' + password + '');
        };

        apiFactory.loginStatus = function () {
            return $http.get(urlBase + '/authentication/is_logged_in/');
        };

        return apiFactory;
    });

 angular.module('controllers.login', [])
    .controller('loginCtrl', function($scope, apiFactory, userValue) {

        var credentials = { username: '',   password: '', remember: ''};

        $scope.login = function(credentials) {
            apiFactory.appLogin(credentials.username, credentials.password)
                .success(function(response){
                    // if loggin susseed
                    userValue.logged_in = true;
                });     
        };
    });
James P
  • 2,201
  • 2
  • 20
  • 30
Maarten Heideman
  • 545
  • 1
  • 9
  • 18
  • Possible duplicate of [AngularJS : Initialize service with asynchronous data](http://stackoverflow.com/questions/16286605/angularjs-initialize-service-with-asynchronous-data) – Estus Flask May 29 '16 at 20:42
  • No, this is not possible, `userValue` is set asynchronously, and bootstrapping is synchronous process. 'Pause the app to wait for X' is one of the most common Angular misconceptions. Use router resolvers to resolve app-wide dependencies. If the router isn't used yet, this is a very good reason to correct this. – Estus Flask May 29 '16 at 20:44

0 Answers0