Note that there are some explanatory texts on larger screens.

plurals
  1. POAngular Service Definition: service or factory
    primarykey
    data
    text
    <p>I am an angular newbie, I am building an application, one thing really puzzling me is there are couple of ways of defining a service, and I read more from this link: <a href="http://iffycan.blogspot.com/2013/05/angular-service-or-factory.html" rel="nofollow">How to define service</a> then it seems there is no big difference among the ways of defining a service.</p> <p>but I just noticed one difference which I think is different:</p> <p>see this service I get from here <a href="http://jsfiddle.net/2by3X/5/" rel="nofollow">http://jsfiddle.net/2by3X/5/</a></p> <pre class="lang-js prettyprint-override"><code>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; }; }); </code></pre> <p>if I define this service using "factory" like below, one function cannot call other functions of the service.</p> <pre class="lang-js prettyprint-override"><code>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; }, }; }); </code></pre> <p>I will get this in the browser console:</p> <pre><code>[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 </code></pre> <p>Can anyone explain this? thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload