场景:我有一个包含以下代码的工厂服务
appServices.factory('MyDB', function ($cordovaSQLite)
{
var FixedCache = [];
return {
getFromCache: function (dataURL, $scope)
{
var query = "SELECT * FROM FixedCache WHERE URI_ID = '"+dataURL+"'";
FixedCache = [];
$scope.dataFromCache = [];
//console.log("Inside Cache method");
// Execute query statement from query variable.
$cordovaSQLite.execute(db, query).then(function (res)
{
if (res.rows.length > 0)
{
var dataItem = {
id : res.rows.item(0).id ,
URI_ID : res.rows.item(0).URI_ID ,
ExpireDate : res.rows.item(0).ExpireDate ,
JSONData : res.rows.item(0).JSONData
};
FixedCache.push(dataItem);
$scope.dataFromCache = FixedCache;
}
});
return FixedCache;
},// End select all data.
};
})
在 Controller 中,我想通过调用这个方法来获取数据。这是 Controller 的代码。
appControllers.controller('categoriesCtrl', function ($scope, $http, $state, $timeout, $stateParams, $ionicHistory, MyDB, UtilityMethods) {
var dataURL = window.globalVariable.constants.URL_API;
$scope.initialForm = function () {
$scope.categoriesFromCache = [];
$scope.categoryCache;
$scope.url = window.globalVariable.constants.URL_API;
$scope.todaysDate = UtilityMethods.GetDate(0);
// $scope.isLoading is the variable use for loading.
$scope.isLoading = false;
$scope.apiUrl = window.globalVariable.constants.URL_API;
};// End initialForm.
$scope.GetFromCache = function (uri, $scope) {
$scope.dataFromCache = [];
MyDB.getFromCache(uri, $scope);
};
$scope.navigateTo = function (targetPage, objectData, apiUrl) {
$state.go(targetPage, {
category: objectData,
apiUrl: apiUrl
});
};
$scope.clearSearch = function() {
$scope.searchByName = '';
};
$scope.goBack = function () {
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go("app.categories", {
isShowError: false
});
};
$scope.initialForm();
$timeout(function () {
$scope.GetFromCache(dataURL, $scope);
}, 3000);// End loading progress.
});
问题: 当我调用此方法时 MyDB.getFromCache(uri, $scope);在 Controller 中,它返回空数组 [] 数据库确实包含数据。
请指导我。我是否正确调用了这些函数?
最佳答案
您的代码不起作用的原因是,您正在考虑异步事件以同步方式工作,尽管我想说将 $scope
作为参数传递给工厂方法并不是被视为良好做法。
基本上,您需要做的是从 Controller 内部 promise 并在其中设置范围变量的方法和链返回cordova promise
。
工厂
getFromCache: function(dataURL) {
var query = "SELECT * FROM FixedCache WHERE URI_ID = '" + dataURL + "'";
FixedCache = [];
//returning cordova promise
return $cordovaSQLite.execute(db, query).then(function(res) {
if (res.rows.length > 0) {
var dataItem = {
id: res.rows.item(0).id,
URI_ID: res.rows.item(0).URI_ID,
ExpireDate: res.rows.item(0).ExpireDate,
JSONData: res.rows.item(0).JSONData
};
FixedCache.push(dataItem);
return FixedCache; //return data to chained promise
}
});
}
Controller
$scope.GetFromCache(dataURL).then(function(data){
$scope.dataFromCache = data;
});
关于javascript - AngularJS 中工厂方法的空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158968/