質問

I developed an app and I've a REST API for fetching app resources from my AngularJS app. When the user logs himself, I save his access token in a cookie. If he refreshes the page, I want to get back user information from the token like:

mymodule.run(function ($rootScope, $cookies, AuthService, Restangular) {
    if ($cookies.usertoken) {
        // call GET api/account/
        Restangular.one('account', '').get().then( function(user) {
            AuthService.setCurrentUser(user);
        });
    }
});

AuthService:

mymodule.factory('AuthService', function($http, $rootScope) {
    var currentUser = null;

    return {
        setCurrentUser: function(user) {
            currentUser = user;
        },
        getCurrentUser: function() {
            return currentUser;
        }
    };
});

But if the user accesses a controller which needs a user variable:

mymodule.controller('DashboardCtrl', function (AuthService) {
     var user = AuthService.getCurrentUser();
});

the controller code was executed before the end of the API call so I've a null var. Is there a good solution to wait on user data loading before starting controllers?

I've found this link but I'm looking for a more global method to initialize app context.

役に立ちましたか?

解決

Here's one way I like to handle this, assuming that Restangular returns the new promise from then (I haven't used Restangular). The promise can be stored somewhere like on AuthService and then used later in the controller. First, add a property to AuthService to hold the new promise:

return {
    authPromise: {},  // this will hold the promise from Restangular
    // setCurrentUser, getCurrentUser
    // ...

When calling Restangular, save the promise and be sure to return the user data so that the controller can access it later, like this:

AuthService.authPromise = Restangular.one('account', '').get()
                          .then( function(user) {
                              AuthService.setCurrentUser(user);
                              return user; // <--important
                           });

Lastly, create a new promise in the controller that will set the user variable.:

mymodule.controller('DashboardCtrl', function (AuthService) {
    var user;
    AuthService.authPromise.then(function(resultUser){
        user = resultUser;
        alert(user);
        // do something with user
    });
});

Demo: Here is a fiddle where I've simulated an AJAX call with $timeout. When the timeout concludes, the promise resolves.

他のヒント

You could try have the authentication method on a parent controller. Then in the resolve method in the routing you could go resolve:DashboardCtrl.$parent.Authenticate().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top