I am new to AngularJs. My question is how to store current user data after user logged in?
I have come across lots of solutions recommending the use of service, and inject the service into controllers. Something like this:
customer.factory('service', function(){
var auth = {};
auth.currentUser = null;
auth.setCurrentUser = function(data){
auth.currentUser = data;
};
return auth;
})
This worked perfectly for me until I hit the refresh button of the browser, all information stored in Javascript variable are lost.
To solve this problem, do I have to use $cookieStore or something similar? I have seen few people mentioning ui-route, I can't quite get my head around it. Is ui-route relevant to this discussion? Also I would like to use the same solution to save authentication token for the logged in user.
What is your general opinion around this issue? Thank you so much in advance.
Ui-route
I think you mean AngularUI Router which is a routing framework for AngularJS. It has got nothing to do with persistent storage.
Services
Angular Services are singletons. It is used to organize and share code across your app. It is instantiated when a component such as a controller needs it. Once you close your app or reload it, the data in it is lost and it is re-instantiated when needed.
Then how to persist data?
Using $cookies
angular.module('app', ['ngCookies']);
$cookies
dependency in you controller or service (where you want to access the cookies)//Getting a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');`
See documentation.
Using HTML5 Local Storage
"With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per domain. All pages, from one domain, can store and access the same data." - via W3Schools
While you can use pure JS for local storage, ngStore is a library that you can use with AngularJS. It provides you with localStorage and sessionStorage .
$localStorage
- stores data with no expiration date
$sessionStorage
- stores data for one session (data is lost when the tab is closed)
Dependency for your app:
angular.module('app', ['ngStorage'
]);
Then
$localStorage.visitorCount = 500;