How to customize service setters and getters in AngularJS

Just starting out with JS and angular, I've created a currentUser service in angular... The goal is to store the current user in the localStorage so it persists between page refreshes

Here's how the service is defined

var currentUserSrvc = function() {
  // logic for saving user to localStorage
  return {
    user: {}
  };
};
angular.module('app').factory('currentUser', currentUserSrvc);

I'm looking to customize the setters and getters for this service to interact with localStorage... but without manually adding setters and getters

Details of the localStorage functionality are not important

// I just want to be able to do
currentUser.user = response.user
// instead of having to use (if setter and getter methods were provided)
currentUser.setUser(response.user)

Is it possible with angular js?

Answer №1

Is this the solution you seek?

var userHandler = function() {
  // operations to manage user data in localStorage

  return {
     get userData() {return localStorage.user;},
     set setUserData(user) {localStorage.user = user}
  };
};
angular.module('app').factory('userModule', userHandler);

This demonstrates how to implement getters and setters in JavaScript:

For example:

userModule.userData // retrieves localStorage.user
userModule.setUserData = "myUser" // sets localStorage.user to "myUser"

EDIT: An alternative approach is as follows.

var userHandler = function() {
  var currentUser = {}
  Object.defineProperty(currentUser, "userData", {
    get: function() {return localStorage.user; },
    set: function(user) { localStorage.user = user; }
  })

  return currentUser;
};
angular.module('app').factory('userModule', userHandler);

Therefore:

userModule.userData // retrieves localStorage.user
userModule.userData = "myUser" // sets localStorage.user to "myUser"

EDIT2: Another option could be:

var userHandler = function() {
  // logic to handle saving user data to localStorage

  return {
     get userData() {return localStorage.user;},
     set userData(user) {localStorage.user = user}
  };
};
angular.module('app').factory('userModule', userHandler);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use AngularJS filters to arrange time?

Currently, I have a timer that is counting down from a user-set value. Users input a number representing minutes, which is then converted to milliseconds by multiplying it by 1000 * 60. The timer then decrements this number as it counts down. My goal is t ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

Is there a delay in using ngShow and ngClick for authentication in AngularJS and Firebase?

Just getting started with AngularJS and encountering an unusual issue with Firebase authentication. The basic setup displays the current user status (logged in or not) along with options to sign in and out. Oddly, when I click the Log-in button for the fi ...

The powerful duo of jQuery and CSS shine brilliantly on iOS devices

I attempted to determine the position of an element from the right side. This is how I defined it in my CSS .container { position: absolute; right: 8%; bottom: 7%; } When trying to get the position using jQuery, I used the following code: $(&ap ...

AFrame: keeping an element's world position and rotation intact while reparenting

I am attempting to reassign a child element (entity) to another parent while preserving its position, rotation, and possibly size in the scene. Ideally, I would like to implement a component (let's call it "reparent") that can be added to an entity to ...

Guide on verifying the status of a switch toggle using Selenium and C#

I am having trouble verifying the current state of a switch ('on' or 'off') using selenium. The toggle appears in the 'on' position when the webpage loads, but it affects filter results in a table when switched off. I am unabl ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...

The ng-table is currently showing all of its data instead of limiting the display to just 10 entries

I have a function that performs calculations using multiple values to populate an ng-table with the results. While everything works correctly, the table should only display 10 values per page for pagination purposes. However, currently, all values are bein ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

Issue with menu display after clicking icon

On my website, I am trying to set up an icon that will display a menu bar for mobile users. I have written some JavaScript code for this functionality, but it's not working as expected. My approach involved creating an element called "Menu" and assign ...

The functionality of Angular2 two-way binding ceases to function once the Google Maps callback is

I am currently working on an Angular 2 application that includes a Google Maps feature with autocomplete functionality. The setup involves an input field (with Google Autocomplete) and a search button. Upon clicking the search button, the input data is sen ...

Ionic 2 development featuring a stylish background image

Hello there, I recently created a mobile app using Ionic version 2. When I run 'ionic serve', I can see the background image and logo of my application on the login page. However, when I build the app, the background image and logo do not appear ...

Tips for utilizing a variable name with ajax in jQuery

Currently, I have the following code that is a part of an autocomplete ajax query. The code is returning JSON and is functioning correctly with the provided code snippet. However, my goal is to enhance the auto complete function by making it more generic ...

Tips for constructing a multi-dimensional entity from an existing object?

Looking to frame an object as a two-dimensional entity. let data = [ {'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1}, {'id':1, 'pri ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

Place a <script> tag within the Vue template

I am currently developing an integration with a payment service. The payment service has provided me with a form that includes a script tag. I would like to insert this form, including the script tag, into my component template. However, Vue does not allo ...

Can you explain the meaning behind this code snippet using spread syntax, the .map method, and .dataset.filter?

I'm currently dissecting this code snippet to understand its functionality. I am particularly puzzled by the use of spread syntax (...document.querySelectorAll) and the purpose of the .map and .dataset.filter methods. const filters = [...document.quer ...

Determine if an Android application has been installed using JavaScript or jQuery

I'm working on an Android app that is also accessible via a web browser. I want to add a banner prompting users to install the Android application if they haven't already. How can I use JavaScript or jQuery to detect if the user has the app insta ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

Enhancing textures in three.js

I am currently working on a project using three.js where I am attempting to change the color texture by clicking on an image. Below is the code I have been using: ... var col; document.getElementById('image3').onclick = function() { col=("te ...