angularjs覆盖服务设置器和getter

时间:2015-01-29 16:53:17

标签: javascript angularjs angular-services angularjs-factory

我是JS和角色的新手, 我有角度的currentUser服务...它应该将检索到的当前用户设置为localStorage以在页面刷新之间保留它

服务定义如下

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

我想覆盖此服务的setter和getter以使用localStorage ...但不手动添加setter和getter

不要介意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)

是否可以使用角度js?

1 个答案:

答案 0 :(得分:4)

这是你在找什么?

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

这是你在javascript中使用getter和setter的方法:

所以你会:

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

编辑:替代方案,你可以这样做。

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

所以你会:

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

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