DaveC426913 DaveC426913 - 18 days ago 4
AngularJS Question

writing a simple Angular Service

OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:

app.js:

var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {

$scope.message = 'I am Angular and I am working.';

var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};

init();

}]);


dataService.js:

(function() {
'use strict';

angular
.module('gridApp')
.service('dataService', dataService)

dataService.$inject = [];

function dataService() {

console.log("I am the dataService and I am loaded");

var foo = 1;

function getData () {
return 2;
}

}
})();


I see this on-screen: I am Angular and I am working. so Angular is loading.

I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.

But then the console.log is:

undefined (line 8)

TypeError: dataService.getData is not a function (line 9)

What am I missing?

Answer

The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:

function dataService() {
  var dataService = this;  //get a reference to the service

  //attach your functions and variables to the service reference
  dataService.foo = 1;
  dataService.getData = function() {
    return 2;
  };
}