I have created an app using Ionic framework that displays articles. When a single article is opened, I use the init
function in the UserService
to initialize user data:
angular.module('coop.services')
.factory('UserService', function(
$http,
AppSettings,
$rootScope,
$auth,
$q,
$resource,
$cordovaFileTransfer
) {
var service = {
user: {},
init: function() {
var user = localStorage.getItem('coop_user');
if (user) {
service.user = JSON.parse(user);
}
service.engagementResource = $resource(
AppSettings.apiUrl + '/user/:userId/engagements',
{
userId: service.user.id
}
);
},
set: function(user) {
service.user = user;
localStorage.setItem('coop_user', JSON.stringify(user));
},
get: function() {
return service.user;
},
// Other functions...
join: function(engagementId){
return service.engagementResource.save({
engagementId: engagementId
});
},
leave: function(engagementId) {
return service.engagementResource.delete({
engagementId: engagementId
});
},
getEngagements: function() {
return service.engagementResource.query();
},
};
service.init();
return service;
});
However, when I access the single article page with a new user, the console shows null
for user data instead of actual data.
init: function() {
var user = localStorage.getItem('coop_user');
console.log(user);
As a result, my requests to the backend fail because user data is not being sent. During login, I store user data in localStorage
in the auth controller
like this:
$scope.loginPromise.then(function(response) {
UserService.set(response.data.user);
The problem is resolved if I refresh the page, as the user data becomes available. How can I resolve this issue?