Beginning AngularJS

(WallPaper) #1
Chapter 7 ■ ServiCeS and Server CommuniCation

■ Note Like other core angular identifiers, built-in services always start with the $ symbol.


The idea of the window object as a service might seem a little odd at first, but it makes perfect sense. It contains
a set of related functions and properties that we want to be readily available across our application. That’s a service!
Additionally, because it is a service, we don’t have to be too concerned about how it goes about its work or how we
might work with it in other contexts. While it may be early days in your Angular career right now, professional-grade
testing is one such context you are likely to encounter in the future.


The $location Service

Based on the window.location object, the $location service parses the URL in the browser address bar and makes it
available to your application. If you make changes to the URL in the address bar, they are reflected in the $location
service, and if you make changes to the $location service, they are reflected in the browser address bar.
At first glance, it might seem like the $location service is merely a reference to the browser’s window.location
object, but it is a little more than this. It has tight integration with the Angular framework’s life-cycle events, and it also
has seamless support for the HTML5 history API (with automatic fallback support for older browsers). As a general
rule, whenever your application needs to respond to a change in the current URL, or you want to change the current
URL in the browser, this is the service to use.


■ Caution the $location service will not cause a full-page reload when the browser urL is changed. in order to


achieve this, you should use the $window.location.href property.


Listing 7-2 is a basic example of the $location service in action. Here, we use it to display the current URL and a
list of URL parts.


Listing 7-2. Using the $location Service


<!DOCTYPE html >




Angular Services


Free download pdf