简体   繁体   中英

angularjs override service setter and getter

I'm new to JS and angular, I have a currentUser service in angular... It should set the current user retrieved to the localStorage to persist it between page refreshes

the service is defined as follows

var currentUserSrvc = function() {
  // some logic on how to save the user to localStorage
  return {
    user: {}
  };
};
angular.module('app').factory('currentUser', currentUserSrvc);

I want to override the setters and getters for this service to work with localStorage ... but without adding setters and getters manually

don't mind how the localStorage internals will work

// I just want to use it like
currentUser.user = response.user
// instead of using it like (given that I'll provide a setter and a getter methods)
currentUser.setUser(response.user)

is that possible using angular js ?

Is this what you are looking for?

var currentUserSrvc = function() {
  // some logic on how to save the user to localStorage

  return {
     get user() {return localStorage.user;},
     set setUser(user) {localStorage.user = user}
  };
};
angular.module('app').factory('currentUser', currentUserSrvc);

This is how you use getters and setters in javascript:

So you would:

currentUser.user //retrieves localStorage.user
currentUser.setUser = "myUser" //sets localStorage.user to "myUser"

EDIT: Alternative you can do this.

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

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

So you would:

currentUser.user //retrieves localStorage.user
currentUser.user = "myUser" //sets localStorage.user to "myUser"

EDIT2: Or you could even do this:

var currentUserSrvc = function() {
  // some logic on how to save the user to localStorage

  return {
     get user() {return localStorage.user;},
     set user(user) {localStorage.user = user}
  };
};
angular.module('app').factory('currentUser', currentUserSrvc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM