Reputation: 509
I am developing an Ionic's mobile app and stuck by the error
TypeError: t.getCases(...).then is not a function
The following are my controller and service concerned:
starter.services.factory('appData', function() {
return {
getCases: function() {
var cases =[
{case_id: 1, description: 'headache'},
{case_id: 2, description: 'fever'},
{case_id: 3, description: 'stomachache'}
];
return cases;
}
}
})
starter.controllers.controller('mainViewCtrl', function($scope, appData) {
appData.getCases().then(function(data){
$scope.cases = data.cases;
});
console.log("mainViewCtrl completed");
})
Please note that I run the gulp script to merge and "uglify" all JS files before building the package file.
Any help would be much appreciated.
Upvotes: 5
Views: 2719
Reputation: 1040
As T.J. Crowder said, in order to use "then" (asynchronous call), you have to return a promise from the service, able to fetch in your controller afterwards:
starter.services.factory('appData', function($q) {
return {
getCases: function() {
var deferred = $q.defer();
var cases =[
{case_id: 1, description: 'headache'},
{case_id: 2, description: 'fever'},
{case_id: 3, description: 'stomachache'}
];
//attach data to deferred object
deferred.resolve(cases);
//return promise to be catched with "then"
return deferred.promise;
}
}
})
If you might want to return an error as callback, you might just reject the promise by calling deferred.reject(error) (while error is an optional error message/object).
Here is another good link which helped me to get the concept of asynchronous programming with promises in angular: $q.defer
Upvotes: 1