Chapter 7 ■ ServiCeS and Server CommuniCation
Why Use Services?
One thing that might have struck you as you read through these examples is that these particular services don’t really
add much in terms of functionality. The $window service, for example, doesn’t appear to add much above and beyond
what the regular JavaScript window object has to offer. While some Angular services, such as the $http and $animation
services (which we will look at in later chapters), are very rich in functionality, what I want to convey in this section
is that services are a core aspect of Angular and, regardless of what functionality a given service may offer, the way in
which we access a service is consistent and offers important architectural benefits.
The $window service offers us the benefit of abstraction; we are not tied specifically to the browser’s window
object. So, in more advanced scenarios, we can actually switch it to use some other implementation. The $location
service offers similar benefits, and it is also designed to work very well with the Angular routing framework (which we
will also be looking at in a later chapter).
Angular services are an important part of how Angular applications are built, because they are a well-architected
approach to managing dependencies, and they go a long way toward making applications much more robust.
It shouldn’t be too hard to start thinking in terms of services, because Angular uses them a lot. With a little time
and experience, you will start to appreciate and realize the benefits of services, and you will develop a deeper
understanding of where and when they should be used.
Creating Services
Angular services provide a mechanism for keeping data around for the lifetime of an application and for
communicating across controllers in a consistent manner. As services are implemented as singletons, which are
objects that are instantiated only once per application, you interact with the same instance of a service every time
you use it. Angular is also performance-conscious, so it will create a service only when you need it and not a moment
before. This is all great news, but it does mean that we must learn the ground rules when we create our own services.
We’ll start off nice and easy with Listing 7-4. All that this service will do is to tell us the current date and the
current time, but it’s just enough to get an idea of how the plumbing works.
Listing 7-4. A Basic Angular Service
<!DOCTYPE html >