Pregunta

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)

.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.

But the console.debug outside readFile, shows it as undefined, why? If it is declared on getTags scope.

¿Fue útil?

Solución

This could be because readFile is asynchronous. 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;
  });
})

Otros consejos

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. So I'm using readFileSync and now it works.

  this.getTags = function() {
    this.t = fs.readFileSync('tags', 'utf8');
    console.debug(this.t);
    return this.t.split(',');
  };
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top