I am new to angular, I am creating an application, I am really puzzled, there are several ways to define a service, and I read more on this link: How to define a service , there seems to be no big difference between the ways to define a service.
but I noticed only one difference, which, in my opinion, is different:
see this service i get from here http://jsfiddle.net/2by3X/5/
var app = angular.module('myApp', []); app.service('test', function($timeout, $q) { var self = this; this.getSomething = function() { return self.getData().then(function(data) { return self.compactData(data); }); }; this.getData = function() { var deferred = $q.defer(); $timeout(function() { deferred.resolve("foo"); }, 2000); return deferred.promise; }; this.compactData = function(data) { var deferred = $q.defer(); console.log(data); $timeout(function() { deferred.resolve("bar"); }, 2000); return deferred.promise; }; });
if I define this service using "factory" as shown below, one function cannot call other functions of the service.
app.factory('test', function($timeout, $q) { return { getSomething : function() { return getData().then(function(data) { return compactData(data); }); }, getData : function() { var deferred = $q.defer(); $timeout(function() { deferred.resolve("foo"); }, 2000); return deferred.promise; }, compactData : function(data) { var deferred = $q.defer(); console.log(data); $timeout(function() { deferred.resolve("bar"); }, 2000); return deferred.promise; }, }; });
I will take this in the browser console:
[08:41:13.701] "Error: getData is not defined .getSomething@http ://fiddle.jshell.net/_display/:47 Ctrl1@http ://fiddle.jshell.net/_display/:75 invoke@http ://code.angularjs.org/1.0.0/angular-1.0.0.js:2795 instantiate@http ://code.angularjs.org/1.0.0/angular-1.0.0.js:2805
Can anyone explain this? thanks.