0

我编写了一个查询数据库并应返回类别的角度服务:

(function() {
    'use strict';
     angular.module('budget')
           .service('CategoriesService', ['$q', CategoriesService]);

    function CategoriesService($q) {
        var self = this;
            self.loadCategories = loadCategories;
            self.saveCategorie = saveCategorie;
            self.datastore = require('nedb');
            self.db = new self.datastore({ filename: 'datastore/default.db', autoload : true});

        function saveCategorie (categorie_name) {
            var entry = {name: categorie_name,
                     type: 'categorie'}
            self.db.insert(entry);
        };

        function loadCategories () {
            self.db.find({type: 'categorie'}, function (err, docs) {
                var categories = docs;
                return categories;
            });
        };

        return {
            loadCategories: self.loadCategories,
            saveCategorie: self.saveCategorie
        };
    }
})();

当我在其中的 console.log 中function loadCategories()返回一个包含 6 个对象(来自数据库的对象)的数组,但在函数之外它只给了我undefined.

我通过控制器调用CategoriesService.loadCategories()

所以我想我可能不得不做一些所谓的事情,promise但我不确定。

如何从该服务中获取实际数据?

4

2 回答 2

1

你需要先回报你的承诺,所以只需再增加一个回报,你就可以走了......

   function loadCategories () {
        // you need to return promise first and you can resolve your promise in your controller
        return self.db.find({type: 'categorie'}, function (err, docs) {
            var categories = docs;
            return categories;
        });
    };
于 2015-12-09T15:21:27.597 回答
1

首先,您不需要从服务工厂配方中返回任何内容,您只需为this变量分配一个方法。

至少,你需要:

// service.js

self.loadCategories = function() {
  var deferred = $q.defer();
  db.find({type: 'categorie'}, function (err, docs) {
    deferred.resolve(docs);
  });
  
  return deferred.promise;
};

// controller.js

service
  .loadCategories()
  .then(function(categories) {
    $scope.categories = categories;
  })
;

于 2015-12-09T15:27:02.837 回答