可以简化提供单个 gettable/settable 变量的服务吗? [英] Can a service that provides a single gettable/settable variable be simplified?
问题描述
我有这样的服务:
var app = angular.module('someModule');
app.factory('token', function() {
var token = null;
return {
get: function() {
return token;
},
set: function(tokenIn) {
token = tokenIn;
}
};
});
我宁愿有这样的东西:
app.variable('token', null);
在 POJO 工作了 5 年之后,我对 getter/setter 有了小而强烈的仇恨.有没有更好的方法来用 angular 做到这一点?provide.constant 和 provide.value 似乎不符合要求.我也找不到可以执行此操作的插件 - 是否有一些我不知道的概念的词汇?
After 5 years of POJOs, I'm have a small but intense hatred for getter/setters. Is there a better way to do this with angular? provide.constant and provide.value didn't seem to fit the bill. I couldn't find a plugin to do this either-- is there some vocabulary for this concept I am ignorant of?
推荐答案
你可以像这样直接使用对象:
You can just use the object directly something like:
myApp.factory('token', function(){
return { Token : '' };
});
然后您可以将 token
工厂注入您的控制器,并按如下方式获取或设置令牌:
Then you can inject the token
factory into your controller and either get or set the token as follows:
myApp.controller("Test", function ($scope, token) {
// set:
token.Token = 'abc';
// or get
var local = token.Token;
});
这与您所能获得的POJO"差不多.希望有帮助!
This is about as close to a "POJO" as you can get. Hope that helps!
这篇关于可以简化提供单个 gettable/settable 变量的服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!