HFA HFA - 29 days ago 7
AngularJS Question

Getting user profile in angular after user logged in

In my application each user has a specific profile, I have created a service to hold this profile named

currentUser
.

I use the properties of this profile to render my the header of site and make further api calls.

the problems is that when should I fill this
currentProfile
service?

There are a few options:

1 - after login promise is resolved:

authService.login(username, pass)
.then(function(response) {
userService.getProfile()
.then(function(profile){
currentUser.setProfile(profile);
$state.go('dashboard');
});
});


the main problem with this approach is that if a user is in this url
/main/list
and refreshes the page,
currentUser
gets emptied.

2 - using ui-router
deferIntercept
and
urlRouter.sync()
and
$urlRouter.listen()
like here , but the main problem with this approach is that my header directive and controller gets executed before (or during) event handler of
$locationChangeStart
and
currentUser
is not filled yet.

How can I achieve my desried effect? any idea is appreceated!

Edit: I don't want to rely on localStorage or cookie or ....

Answer

Use ui-router , it has a resolve property which ensures data is loaded before the application continues.

$stateProvider
        .state('main.list', {
            url: "/main/list",
            templateUrl: "views/custom/index.html",
            controller:MainController,
            resolve: {
                loginUser : function($q){
                  var promise = $q.defer()
                  //load data or whatever
                   loadData().then(function(data){
                     promise.resolve(data);
                   })
                  return promise.promise;
                }
            }
        })

Comments