AngularJS Lazy Instantiation – Services are only instantiated when required by application components.
In a typical application, numerous services may be created but remain dormant until needed. Consider the code snippet below:
var app = angular.module('app', [])
app.service('test', function() {
this.xyz = function() {
return one;
};
});
Here, the test
service is defined but remains inactive.
var app2 = angular.module('app2', ['app'])
app2.service('test2', function(test) {
this.xyz = test.xyz();
});
When the test2
service depends on test
, Angular instantiates test
prior to executing test2
. If test2
does not utilize test
, it will not be instantiated. The same applies to test2
; if unused, it remains inactive.
Singleton Pattern – Each component that relies on a service accesses a single instance generated by the service factory.
Consider a scenario where you need a service to send analytics from your webpage to a server. Rather than creating new instances each time the service is injected, the same instance is utilized throughout the application. This illustrates the Singleton pattern in action, ensuring a single instance is shared across all injections of the service.
Conversely, imagine a User class where distinct instances are required for each user. In such cases, utilizing a Service may not be suitable, and a factory
should be employed instead.