Ionic Controller and Service: “TypeError:… is not a function”

I am developing an Ionic’s mobile app and stuck by the error

TypeError: t.getCases(…).then is not a function

  • Inject code in inApp browser and get it's return value in the app
  • calling javascript from eclipse for PhoneGap
  • Phone gap 3.0 + sencha touch open urls in device browser
  • TypeError “Cannot set property connection of #<Navigator>” in console when upgrading project to latest version of Cordova 4.0.0
  • How to use custom cordova plugin in ionic project?
  • Preventing TouchCancel events in Android Cordova Application
  • The following are my controller and service concerned:

    Service

    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;
        }
      } 
    
    })
    

    Controller

    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.

  • Phonegap 3.0 - Android: Native Scrollbar Not Visible
  • mouseOver on touch screen
  • How can I focus on an input field when a phonegap page loads?
  • Phonegap with Compass and GPS coordinates
  • Remove splash screen manually in PhoneGap
  • JQuery Mobile and Cordova Page Templates
  • One Solution collect form web for “Ionic Controller and Service: “TypeError:… is not a function””

    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