Javascript 返回AngularJS中的值
我编写了一个angular服务,它查询db并应返回类别:Javascript 返回AngularJS中的值,javascript,angularjs,nedb,Javascript,Angularjs,Nedb,我编写了一个angular服务,它查询db并应返回类别: (function() { 'use strict'; angular.module('budget') .service('CategoriesService', ['$q', CategoriesService]); function CategoriesService($q) { var self = this; self.loadCatego
(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
};
}
})();
当我在函数loadCategories()
中运行console.log时,它会返回一个包含6个对象(来自数据库的对象)的数组,但在函数之外,它只会给我未定义的
我使用CategoriesService.loadCategories()通过控制器呼叫
所以我想我可能不得不做一些被称为“承诺”的事情,但我对此不确定
如何从该服务中获取实际数据?您需要先返还您的承诺,因此只需再添加一次返还,您就可以继续
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;
});
};
首先,您不需要从service factory recipe返回任何内容,只需要为这个
变量分配一个方法
至少,您需要:
//service.js
self.loadCategories=函数(){
var deferred=$q.deferred();
db.find({type:'categorie'},函数(err,docs){
延期。解决(单据);
});
回报。承诺;
};
//controller.js
服务
.loadCategories()
.然后(功能(类别){
$scope.categories=类别;
})
;代码>你需要承诺是正确的。读这篇文章:为什么他想用$q来包装他的承诺?