簡體   English   中英

Angular服務試圖從文件中讀取數據(我正在使用node-webkit),無法使其正常工作

[英]Angular service, trying to read data from file (I'm using node-webkit), can't get it to work

我已經嘗試了一段時間,並瀏覽了幾個答案,但無法弄清楚為什么它不起作用:

我需要在控制器之間共享一些數據,所以我要設置服務嗎? (數據是從文件獲取的,我使用的是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;
  };

})

然后在某些控制器中我會做

.controller('sidebarCtrl', function($scope, tagList) {
  $scope.tags = tagList.getTags();
})

但是標簽最終以undefined結束, readFileconsole.debug都顯示了它應該如何。

但是readFile之外的console.debug ,顯示為undefined ,為什么? 如果在getTags范圍內聲明。

這可能是因為readFile是異步的。 嘗試這樣的事情:

.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();
  };    
})

然后像這樣使用它:

.controller('sidebarCtrl', function($scope, tagList) {
  tagList.getTags().then(function(tags){
    $scope.tags = tags;
  });
})

沒關系,修復它。

問題是readFile是異步的,因此當我調用tags ,尚未讀取文件,因此沒有數據存儲在變量中。 所以我正在使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM