service.js
.factory('EventService', function ($http, $cordovaSQLite) {
return {
//some code here..
populateData: function (data) {
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
return items;
}
}
})
Run Code Online (Sandbox Code Playgroud)
controller.js
.controller('NearCtrl', function ($scope, $http, $cordovaSQLite, EventService) {
EventService.getDataFromDB().then(function (result) {
if (result.length > 0) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
} else {
EventService.getDataFromApi().then(function () {
EventService.getDataFromDB().then(function (result) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
})
})
}
});
})
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时,我得到"TypeError:EventService.populateData(...).然后不是函数".
我究竟做错了什么 ?谢谢.
fwh*_*nin 25
该服务需要返回一个承诺,而不是返回项目
populateData: function(data) {
var deferred = $q.defer();
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
deferred.resolve(items);
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
你可能不需要这个,但你可以做到
var items = EventService.populateData(result);
//Do something with items here
Run Code Online (Sandbox Code Playgroud)
如果你是异步做某事,通常会使用promises.就像调用API并等待响应一样.在这些情况下,响应可能需要几秒钟才能完成.then函数被调用.在你的情况下,如果你使该功能成为一个承诺,它几乎会立即被调用
编辑:这是$ q文档AngularJS的链接:API:$ q
返回有承诺的内容或只是更改您的调用代码:
populateData: return $http.get("www");
Run Code Online (Sandbox Code Playgroud)
或者
EventService.getDataFromApi().then(function () {
EventService.getDataFromDB().then(function (result) {
var response = EventService.populateData(result);
$scope.items = response;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52513 次 |
| 最近记录: |