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;
}
}
})
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;
})
})
})
}
});
})
When I'm trying to run this code, I get "TypeError: EventService.populateData(...).then is not a function".
What am I doing wrong?
The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise. The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
The then() method returns a Promise . It takes up to two arguments: callback functions for the success and failure cases of the Promise .
onclick is not a function" error occurs, because there is no onclick() function in jQuery. To solve the error, use the click function instead, e.g. $('#btn'). click(function () {} .
A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.
that service needs to return a promise, not returning the items
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;
}
you might not need this though since you could do
var items = EventService.populateData(result);
//Do something with items here
usually promises are used if you're doing something asynchronously. Like calling an API and waiting for a response. In those cases, the response might take seconds to finish THEN the .then function gets called. in your case if you make that function a promise it will be called almost immediately
EDIT: Here's the link to $q Documentation AngularJS: API: $q
Return something that has a promise or just change your calling code:
populateData: return $http.get("www");
or
EventService.getDataFromApi().then(function () {
EventService.getDataFromDB().then(function (result) {
var response = EventService.populateData(result);
$scope.items = response;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With