jgravois
jgravois

Reputation: 2579

AngularJS: Unable to access a service method

I am just learning how to use services to slim down my controllers.

I created a plunker and I am returning this error: Error -- TypeError: undefined is not a function pointing to this line ".then(function(crops){"

Here is my index.html (pretty simple)

<body ng-controller="MainController">
    <pre>{{selectedCrops | json}}</pre>
</body>

and here is script.js

(function(){
  angular.module('app',[]);

  angular.module('app')
    .service('LoanSvc', function($http, $q){
      this.getSelectedCrops = function(){
        return {
          show_corn: true,
          show_beans: true,
          show_sorghum: true,
          show_wheat: true,
          show_cotton: true,
          show_rice: true,
          show_peanuts: true,
          show_sugarcane: true
        };
      }
    });

  angular.module('app').controller('MainController', function($scope, LoanSvc){
    LoanSvc.getSelectedCrops()
      .then(function(crops){
        $scope.selectedCrops = crops;
      })
  });
}());

Any guidance is coveted!

Thanks in advance.

Upvotes: 0

Views: 65

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

Since your service doesn't make any HTTP queries and just returns an object with data, you do not need to use the .then() with the return value for LoanSvc.getSelectedCrops().

Instead, you can just use the value directly in your controller:

$scope.selectedCrops = LoanSvc.getSelectedCrops();

Eventually, you will probably want to modify your service to get the data from the server. This is why you inject $http into the service. So you might modify your LoanSvc.getSelectedCrops() function to use $http.get() which returns a $promise. When you do that, you will be able to use the then() function to handle the asynchronous response from the server.

You might modify your service something like this to query a server:

angular.module('app')
    .service('LoanSvc', function($http, $q){
      this.getSelectedCrops = function(){
          return $http.get('some_url/get_crops');
});

Upvotes: 1

Related Questions