简体   繁体   中英

AngularJS documentation: factory function not returning anything

The AngularJS Developer Guide states :

The service factory function generates the single object or function that represents the service to the rest of the application.

Then the following example is given:

batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
function($route, batchLog, $rootScope) {
  $rootScope.$on('$routeChangeSuccess', function() {
  batchLog($route.current ? $route.current.template : null);
});
}]);

Here the factory function is:

function($route, batchLog, $rootScope) { /* ... */ }

but the body of this function doesn't seem to return neither a function nor an object, which seems to contradict the given definition of a factory function. Shouldn't the given factory function end with a return statement and return either a function or an object to meet the definition of factory function? Can someone kindly explain where I am going wrong?

Thanks.

Source of question

In angular factories and services are singleton, ie only one instance will exists. Factory returns that object and in case of Service , it is instantiated behind the scene.

You have to do something like

batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
  function($route, batchLog, $rootScope) {
     var factory = {
          doSomething: function () {
             // do something
          }
      };
     return factory;
  });
}]);

Farther form the same docs:

Note that you are not registering a service instance , but rather a factory function that will create this instance when called.

You can do like this but injected factory instance will be undefined (there's no return statement), so there's no much sense.

Heading of that part of docs is named "Dependencies", so code example there shows how you can inject factory batchLog into routeTemplateMonitor factory. Internals of factories are not important here.

The best place for routeTemplateMonitor content is in run blocks IMO.

You can return whatever you want, but in a factory the function will run only once when you inject your factory somewhere. A function that lacks an explicit return statement will return undefined,

You can return a function and use it, you can return an object with methods and use it, but the important things is that will run only once.

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