Angularjs,从工厂返回的未定义数据

时间:2015-01-09 03:47:24

标签: angularjs

只是一个简单的问题。

我有 factory

 angular.module('app.services').factory('DatabaseFactory', 
 function($log, $q, DB_CONFIG, CATEGORY_CONFIG, $http, $webSql) {
  var self = this;
  self.db = null;

  self.init = function() {
    self.db = $webSql.openDatabase (DB_CONFIG.name, '1.0', 'database', 2 * 1024 * 1024);
    self.db.createTable('QuestionIndex', {
      'id':{
        'type': 'INTEGER',
        'null': 'NOT NULL', // default is 'NULL' (if not defined)
        'primary': true, // primary
        'auto_increment': true // auto increment
      },
      'question_id': {
        'type': 'INTEGER'
      },
      'oltre': {
        'type': 'INTEGER'
      },
      'section_id': {
        'type': 'INTEGER'
      },
      'errors_count': {
        'type': 'INTEGER'
      },
      'done_count': {
        'type': 'INTEGER'
      }

    }); 

  };

  self.getAll = function() { 
    self.db.select('QuestionIndex',{"oltre":'IS NOT NULL'}).then(function(results) {
      var records = [];
      for(var i=0; i < results.rows.length; i++){
        records.push(results.rows.item(i));
      };
      $log.info(records); 
      return records;
    }); 
  };

  return self;

});

我正在另一家工厂注入这个工厂,我必须检索调用getAll函数的数据。

angular.module('app.services')
  .factory('QuizCreate', ['DatabaseFactory','$log', function(DatabaseFactory,$log){
    self.generateQuiz = function() {
      $log.info(DatabaseFactory.getAll());
    };
    return self;
  }]);

第一个日志条目返回所有对象,查询工作正常。我无法理解为什么我的第二个日志会返回undefined

为什么我无法从第一个工厂返回我的数据?

2 个答案:

答案 0 :(得分:0)

它(数据库查询)异步运行,因此return内的.then()语句在$log.info执行之前未被命中。

我会按如下方式对其进行修改:

DatabaseFactory:

self.getAll = function() { 
    return self.db.select('QuestionIndex',{"oltre":'IS NOT NULL'}).then(function(results) {
      var records = [];
      for(var i=0; i < results.rows.length; i++){
        records.push(results.rows.item(i));
      };
      $log.info(records); 
      return records;
    }); 
  };

QuizCreate Factory

self.generateQuiz = function() {
      DatabaseFactory.getAll().then(function(result){
        $log.info(result);
      });
};

答案 1 :(得分:0)

您致电DatabaseFactory.init()了吗?我没有看到它被随处召唤

相关问题