When does AngularJS service get reinitialized?

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

+3


source to share


2 answers


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

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

      


When you try to start a controller or something that depends on a specific 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 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 what it needs to insert User

into FirstCtrlConstructor

, it calls $injector.get('User')

to get User

. Since it hasn't entered User

anywhere else yet, it will fall into an "if not" state and:



  • Challenge new User()

    .
  • Save it $injector.cached

    for next time.
  • Return it.

Now let's say we need to enter a User

second time:

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

      

Again, when Angular sees which SecondCtrlConstructor

depends on User

, it calls $injector.get('User')

to get User

so that it can insert it. This time he gets into the "if it" state. As we previously placed User

in $injector.cached

, he found it there for us. So it User

doesn't get the instance again.

Let's say we have ThirdCtrl

one that also depends on User

. It would find it in too $injector.cached

, and so it won't instantiate UserConstructor

. Let's say that myDirective

depends on User

. The same will happen - it will find it in $injector.cached

and thus not instantiate it.

This is called the Singleton pattern . It was used when you don't want to create something more than once. Angular uses this for services, so they don't get an instance more than once. The same is true for factories (and probably also true for vendors, possibly not matching values ​​and constants).

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

+6


source


Services / factories are initialized only once, on first use. From the docs: https://docs.angularjs.org/guide/services



Angular:

  • Len instance - Angular only creates a service when an app component depends on it.
  • Singletons - Each component that depends on a service gets a reference to a single instance created by the factory service.
+3


source







All Articles