返回 AngularJS 中的值

Returning a value in AngularJS

我写了一个 angular 查询数据库的服务,应该 return 类别:

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

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

我正在通过控制器使用 CategoriesService.loadCategories()

进行呼叫

所以我想我可能必须做一些叫做 promise 的事情,但我不确定。

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

您需要先 return 您的承诺,所以再添加一个 return 就可以了...

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

首先,您不需要 return 服务工厂配方中的任何内容,您只需将方法分配给 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;
  })
;