[英]Angular service, trying to read data from file (I'm using node-webkit), can't get it to work
I've been trying for a while and looked through several answers, I can't figure out why this is not working: 我已经尝试了一段时间,并浏览了几个答案,但无法弄清楚为什么它不起作用:
I need to share some data between controllers, so I set up a service right? 我需要在控制器之间共享一些数据,所以我要设置服务吗? (The data is obtained from a file, I'm using node-webkit)
(数据是从文件获取的,我使用的是node-webkit)
.service('tagList', function() {
this.getTags = function() {
var t;
fs.readFile('tags', 'utf8', function(err, data) {
if (err) throw err;
console.debug(data.split(','));
t = data.split(',');
});
console.debug(t);
return t;
};
})
Then in some controller I'd do 然后在某些控制器中我会做
.controller('sidebarCtrl', function($scope, tagList) {
$scope.tags = tagList.getTags();
})
But tags ends up as undefined
, the console.debug
inside readFile
both show t how it should be. 但是标签最终以
undefined
结束, readFile
的console.debug
都显示了它应该如何。
But the console.debug
outside readFile
, shows it as undefined
, why? 但是
readFile
之外的console.debug
,显示为undefined
,为什么? If it is declared on getTags
scope. 如果在
getTags
范围内声明。
This could be because readFile
is asynchronous. 这可能是因为
readFile
是异步的。 Try something like this: 尝试这样的事情:
.service('tagList', function($q) {
var d = $q.defer();
this.getTags = function() {
fs.readFile('tags', 'utf8', function(err, data) {
if (err) throw err;
console.debug(data.split(','));
d.resolve(data.split(','));
});
return d.promise();
};
})
and then use it like this: 然后像这样使用它:
.controller('sidebarCtrl', function($scope, tagList) {
tagList.getTags().then(function(tags){
$scope.tags = tags;
});
})
Nevermind, fixed it. 没关系,修复它。
Problem was readFile
is asynchronous, so when I was calling tags
, the file wasn't read yet, so no data was stored in the variables. 问题是
readFile
是异步的,因此当我调用tags
,尚未读取文件,因此没有数据存储在变量中。 So I'm using readFileSync
and now it works. 所以我正在使用
readFileSync
,现在它可以工作了。
this.getTags = function() {
this.t = fs.readFileSync('tags', 'utf8');
console.debug(this.t);
return this.t.split(',');
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.