Store user data after login Angularjs

Asked

Viewed 452 times

0

I am logging in through an AJAX request normally using $http, right after logging in, my webservice returns the ID of the logged-in user, so I make another request to pick up this user.

With this user’s data I store the user’s ID and Name.

localStorageService.set('first_name',user.user_first_name);
localStorageService.set('id',user.user_id);

And a few lines above I put the user name in a $Scope variable:

$scope.first_name = localStorageService.get('first_name');

But my big problem is, right after the login I redirect the user to the home ('/') of my system and there I want to display a message: 'Hello so-and-so' (user name). But the problem is that comes without the user name, but I clicking on any other route, for example: ('/panel'), the name is updated in the headere there it appears as I would like.

I think I must be getting lost during the loading of the application.

In short: if there is another better way to do this I change here, I just want to save my user’s data after logging in and display when needed.

1 answer

2

There are two options that would be:
-use $rootScope -> http://docs.angularjs.org/api/ng.$rootScope
-use services -> http://docs.angularjs.org/guide/services

I recommend using the service because there are problems involving global variables.

An example of services:

var myApp = angular.module('myApp',[]);
myApp.factory('Usuario', function() {
  return {
    first_name : 'anonymous'
  };
});

Set values:

Usuario.first_name = 'Nome aqui';

Use in controller:

function MyCtrl($scope, Usuario) {
   $scope.nome = Usuario.first_name;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.