简体   繁体   English

从AngularJS工厂返回功能

[英]Returning function from AngularJS factory

I'm trying to understand what the purpose is of the return part of this AngularJS factory method means? 我试图了解这个AngularJS工厂方法的返回部分的目的是什么意思?

return {
    getMessages: getMessages
  };

What happens if we added a new method to this factory called getAnotherMessage(), would we need to update this return segment? 如果我们向这个名为getAnotherMessage()的工厂添加了一个新方法会发生什么,我们是否需要更新这个返回段?

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是一个提供者构造函数:

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. factory(fn) - 注册一个服务工厂函数fn,它将包装在一个服务提供者对象中,其$ get属性将包含给定的工厂函数。

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. 因此,当Angular首次加载工厂时,它会执行传入的函数并存储作为提供程序返回的任何内容。

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. 上面获取了对getMessage函数的引用,并将其附加到返回的singleton对象中的属性getMessages

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). 然后,当将提供程序注入到代码中时,返回的对象就是传递的内容,使您可以访问HelloWorld.getMessages函数(以及返回对象中的任何其他属性)。

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;   
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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