【发布时间】:2015-07-01 16:01:05
【问题描述】:
我正在开发一个 AngularJS 应用程序并发现以下行为。
我的服务中有两个功能。第一个函数返回存储在数据库中的所有类别,第二个函数通过其 id 返回一个类别。
这是我的服务:
angular.module('categoriesRepository', [])
.service('categoriesRepository', ['$cordovaSQLite', 'sqliteHelper',
function ($cordovaSQLite, sqliteHelper) {
//this works - returns an array with all categories
this.getAll = function () {
var categories = [];
$cordovaSQLite.execute(sqliteHelper.getDb(),
"SELECT * FROM categories;")
.then(function (res) {
for (var i = 0; i < res.rows.length; i++) {
categories.push(res.rows[i]);
}
});
return categories;
}
//this works not - returns undefined
this.getById = function (id) {
var category;
$cordovaSQLite.execute(sqliteHelper.getDb(),
"SELECT * FROM categories WHERE id = ?;", [id])
.then(function (res) {
category = res.rows[0];
});
return category;
}
}]);
我知道我可以使用 Angulars $q 异步运行函数,并在完成处理时使用它们的值。
为什么getById函数直接返回category,getAll等到数组填满?
编辑
我把 getAll 函数贴错了。 $cordovaSQLite.execute之前没有return语句
【问题讨论】:
标签: javascript angularjs