Dinoel Vokiniv
Dinoel Vokiniv

Reputation: 169

angularjs , wait for authorization result before go to next controllers

Hello i have simple LoginService that looks like that:

this.notifyAuthorization = function() {
    console.log('notifyAuthorization()');

    $http({
        url: 'app/?cmd=authorization/',

    }).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data);
        var data = response.data;

        if(data.hash !== undefined) {
            $rootScope.loginStatus= true;
            hash = data.hash;
        }
    });
};

here is the call for the service

app.run(function($rootScope, $location, LoginService) {
    LoginService.notifyAuthorization();
    console.log('notifyAuthorization Finished');
});

Before seeing LoginStatusResult i see notifyAuthorization Finished and other controllers are initialized that should know the LoginStatus so how to solve this ? or is there a better practice ? Thanks

Upvotes: 0

Views: 64

Answers (1)

illeb
illeb

Reputation: 2947

Use promises, which are given by default by your $http function:

this.notifyAuthorization = function() {

    return http({ //notice the return inserted here
        url: 'app/?cmd=authorization/',

    }).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data);
        var data = response.data;

        if(data.hash !== undefined) {
            $rootScope.loginState = true;
            hash = data.hash;
        }
    });
};

and use it properly in your app.run:

app.run(function($rootScope, $location, LoginService) {       
   LoginService.notifyAuthorization().then(function(){
        $rootScope.authorized = true;; //executed after your $http request...
   });
});

and in your html code:

<div ng-controller="myController" ng-if="$root.authorized"> 
    <!-- your inner code..

         <p>Pellentesque habitant morbi tristique senectus et netus et                 
         malesuada fames ac turpis egestas. Vestibulum tortor quam, 
         feugiat vitae, ultricies eget, tempor sit amet, ante. </p>             
    -->
</div>

This way, your controller will be instantiated only after the .then function has resolved

Upvotes: 2

Related Questions