简体   繁体   中英

Returning function from AngularJS factory

I'm trying to understand what the purpose is of the return part of this AngularJS factory method means?

return {
    getMessages: getMessages
  };

What happens if we added a new method to this factory called getAnotherMessage(), would we need to update this return segment?

myModule.factory('HelloWorld', function($q, $timeout) {

  var getMessages = function() {
    var deferred = $q.defer();

    $timeout(function() {
      deferred.resolve(['Hello', 'world!']);
    }, 2000);

    return deferred.promise;
  };

  return {
    getMessages: getMessages
  };

});

factory is a provider constructor:

factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.

Thus when the factory is first loaded by Angular it executes the function that's passed in and stores whatever is returned as the provider.

In other words, the following is run once, and only once- during bootstrapping:

var getMessages = function() {
   var deferred = $q.defer();

   $timeout(function() {
      deferred.resolve(['Hello', 'world!']);
   }, 2000);

   return deferred.promise;
 };

return {
   getMessages: getMessages
 };

The above gets a reference to the getMessage function and attaches it to the property getMessages inside the returned singleton object.

When the provider is then injected into your code, that returned object is what is passed in giving you access to the HelloWorld.getMessages function (and any other properties in the returned object).

So, yes, if you want to associate another property, such as a function, with the provider (that the factory constructs) you need to include it as a property of the returned singleton object:

return {
   getAnotherMessage: function() { ... },
   getMessages: getMessages
 };

You can also declare an empty object first and add functions into the object
and finally return the object.

 myModule.factory('HelloWorld', function($q, $timeout) {   
   var myobject = {};   
   myobject.getMessages = function() {    ...   };   
   myobject.getAnotherMessages = function() {    ...   };

   return myobject;   
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM