Bigman
Bigman

Reputation: 1473

angularjs XXXService.XXXfunction is not a function

It is my first try writing up a service in AngularJS. I have a service, in which I have a function. When I call this service from my controller, it says XXXService.XXXfunction is not a function.

My Javascript is like,

var sharecycle0_angularfire = angular.module("sharecycle0_angularfire", []);

sharecycle0_angularfire.service("baseHttp", function($http, $q){


  self.getFire = function(){

      var deferred = $q.defer();

      $http({
        method: GET,
        url: "https://boiling-inferno-1234.firebaseio.com/Cat"
      }).then(function(response){
        deferred.resolve(response);
      },function(response){
        deferred.reject(resposne);
  });

  return deferred.promise;

  };

});

sharecycle0_angularfire.controller("angularfirecontroller", function($scope, baseHttp, $window){

  $scope.fireClick = function(){

      baseHttp.getFire()
      .then(
          function(response)
          {
              $("<div/>").text(response).appendTo($("#successData"));
          },
          function(response)
          {
              $window.alert("error: "+response);
          }
      );

  };

});

My HTML is like,

<body ng-controller="angularfirecontroller">
    <button id="fireClickButton" ng-click="fireClick()">fireClick</button>
    <div id="successData"/>
</body>

I expect the service code to run upon my button being hit.

Upvotes: 1

Views: 1240

Answers (1)

PSL
PSL

Reputation: 123739

You have some issues here, you are not attaching the function getFire to the service instance, instead you are attaching it to the global variable self. self global variable is generally an alias to window object in many browsers so you are attaching the function to the window and not to the controller instance. Since http already returns a promise you do not need to create a deferred object there, instead just return the result of $http. Apart from that GET needs to be a string value, you are trying to use an undefined variable GET and not "GET". Many a times placing a debug log in relevant areas of the code will help you diagnose the issue.

All you would need is:

sharecycle0_angularfire.service("baseHttp", function($http, $q){
  this.getFire = function(){
      return $http({
        method: 'GET',
        url: "https://boiling-inferno-1234.firebaseio.com/Cat"
      });
    }
});

if you intended to cache this then you should create a local variable and assign this to that.

i.e

sharecycle0_angularfire.service("baseHttp", function($http, $q){
  var _this = this; //Or var self = this
  _this.getFire = function(){
      return $http({
        method: 'GET',
        url: "https://boiling-inferno-1234.firebaseio.com/Cat"
      });
    }
});

Upvotes: 1

Related Questions