Chapter 7 ■ ServiCeS and Server CommuniCation
Using Services
As I mentioned before, Angular ships with a set of useful built-in services. We won’t look at all of them in this chapter,
but we will look at a few; just enough to get a sense of what is offered and how to put them into action.
The $window Service
The $window service is essentially a reference to the browser’s window object. Access to the web browser’s window
object is globally available in JavaScript using the built-in window reference, but it is generally considered best practice
to avoid it when using Angular, because it can cause testability issues. If instead we refer to it through the $window
service, we keep our options open. For example, if we want to test our service in a non-browser context in which the
browser’s window object does not exist, we can more easily switch the underlying service provider to one that uses an
alternate implementation, one which has all of the same properties and methods as the original.
Unfortunately, the use of service providers and advanced testing techniques is not covered in this book, but the
real takeaway here is that, by using a service, we are creating an abstraction that shields us from being intimately
tied to a specific implementation. The service simply does what we ask it to do, and users of the service don’t have to
worry too much about how it does this or even if it changes how it does this.
If you look through Listing 7-1, you will see that we access the $window service through the controller method’s
anonymous function. Here, we specify $scope as the first argument, as we have done on a number of occasions
before, and then we ask for the $window service by specifying it here too.
Listing 7-1. The $window Service
<!DOCTYPE html >
Window width: {{winWidth}}px
An important point here is that we didn’t actually instantiate this service ourselves. The Angular dependency
management sub-subsystem took care of that for us behind the scenes. This technique is an aspect of something
known as dependency injection, a relatively involved topic that is beyond the scope of this book. For now, though, it is
enough to know that asking for a service in this way, as opposed to you declaring and instantiating it yourself within
your controller code, is a major benefit. That being said, you will get a little more insight into the mechanism at play
here when we create our own service in the next section.