Girish Girish - 3 months ago 20
Javascript Question

Error: Not a function - Angular Service

I tried to call function defined in a service.

var app= angular.module('title', ['flash', 'ngAnimate', 'ngRoute'], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');


})

.service('getWidgets', function (globalServices, $http) {
var getData = function() {
var getWidgetUrl = globalServices.baseUrl + "admin/widget/list-text-widget";
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:getWidgetUrl}).then(function(result){

// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};


return { getData: getData };
});


Calling section

var widget = getWidgets.getData();
widget.then(function (result) {
$scope.widgets = result;
$scope.$apply();
});


But it return an error
getWidgets.getData is not a function
.

What would be the root cause?

Answer

Change with this:

angular.module('dss')
  .controller('widgetCtrl', 
    ['$scope', '$compile', '$window', '$location', '$http', 'globalServices', 'getWidgets', 'Flash', '$timeout', '$sce', '$routeParams', widgetCtrl]); 

   function widgetCtrl($scope, $compile, $window, $location, $http, globalServices, getWidgets, Flash, $timeout, $sce, $routeParams) { 

   var widget = getWidgets.getData(); 
   widget.then(
      function (result) { 
          $scope.widgets = result; $scope.$apply(); 
      });     
}