9

What is the lifecycle of a service (or factory) in angularjs and when is it re-initialzed ?

Sam Hosseini
  • 813
  • 2
  • 9
  • 17
vjain27
  • 3,514
  • 9
  • 41
  • 60

2 Answers2

11

When Angular bootstraps, it attaches the constructor functions for services to the associated module. This happens once.

angular
  .module('myApp')
  .service('User', function UserConstructor() {
    // stuff
  });

When a you try to run a controller or something that depends on a certain service, Angular will inject it for you.

app.controller('FirstCtrl', function FirstCtrlConstructor(User) {
  // User is available here
});

Under the hood, angular uses this thing called $injector to do dependency injection for you. It works something like this:

var $injector = {};
$injector.cached = [];
$injector.get = function(service) {
  // check if service is in this.cached
    // if so, return it
    // if not
      // 1) instantiate the service
      // 2) store it in this.cached
      // 3) return it
};

So when Angular sees that it needs to inject User into FirstCtrlConstructor, it calls $injector.get('User') to get the User. Since it hasn't injected User anywhere else before, it'll hit the "if not" condition and:

  1. Call new User().
  2. Store it in $injector.cached for next time.
  3. Return it.

Now let's say that we need to inject User a second time:

app.controller('SecondCtrl', function SecondCtrlConstructor(User) {
  // stuff
});

Again, when Angular sees that SecondCtrlConstructor depends on User, it calls $injector.get('User') to get the User so it could inject it. This time, it hits the "if so" condition. Since we previously put User in $injector.cached, it found it there for us. Thus, User doesn't get instantiated again.

Say we have a ThirdCtrl that also depends on User. It too would find it in $injector.cached, and so it wouldn't instantiate UserConstructor. Say that we have myDirective that depends on User. The same thing would happen - it'd find it in $injector.cached and thus wouldn't instantiate it.

This is called the Singleton pattern. It's used when you don't want to instantiate something more than once. Angular uses this for services so they don't get instantiated more than once. The same is true for factories (and probably also true for providers; probably not true for values and constants).

See https://medium.com/@adamzerner/dependency-injection-in-angular-18490a9a934 for some more info.

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
6

Services/factories are only initialized once, the first time they are used. From the docs: https://docs.angularjs.org/guide/services

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
mofojed
  • 1,342
  • 9
  • 11