Mastering Web Application

(Rick Simeone) #1

Angular Zen


The idea of being able to declaratively express dependencies is a very powerful one;
it frees objects from having to worry about collaborating objects' lifecycles. Even
better, all of a sudden it is possible to swap collaborators at will, and then create
different applications by simply replacing certain services. This is also a key
element in being able to unit test components effectively.


Benefits of dependency injection


To see the full potential of a system integrated using dependency injection,
let's consider an example of a simple notification service to which we can push
messages and retrieve those messages later on. To somewhat complicate the
scenario, let's say that we want to have an archiving service. It should cooperate
with our notifications service in the following way, as soon as the number of
notifications exceeds a certain threshold the oldest notifications should be pushed
to an archive. The additional trouble is that we want to be able to use different
archiving services in different application. Sometimes dumping old messages to
a browser's console is all that is needed; other times we would like to send expired
notifications to a server using XHR calls.


The code for the notifications service could look as follows:


var NotificationsService = function () {
this.MAX_LEN = 10;
this.notificationsArchive = new NotificationsArchive();
this.notifications = [];
};

NotificationsService.prototype.push = function (notification) {

var newLen, notificationToArchive;

newLen = this.notifications.unshift(notification);
if (newLen > this.MAX_LEN) {
notificationToArchive = this.notifications.pop();
this.notificationsArchive.archive(notificationToArchive);
}
};

NotificationsService.prototype.getCurrent = function () {
return this.notifications;
};
Free download pdf