简体   繁体   English

angularjs覆盖服务设置器和获取器

[英]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 我是JS和angular的新手,我在angular中有一个currentUser服务。它应该将检索到的当前用户设置为localStorage以在页面刷新之间持久保存该用户

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 我想重写此服务的setter和getter以便与localStorage ...但不手动添加setter和getter

don't mind how the localStorage internals will work 不在乎localStorage内部如何工作

// 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 ? 使用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: 这是您在javascript中使用getter和setter的方法:

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: EDIT2:或者您甚至可以这样做:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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