Chapter 4. Models and services
This chapter covers
- The vital role that models and services play
- Different types of services and how to create them
- Using $http to communicate with remote servers
- How promises handle asynchronous communication
- Using $http interceptors
- How to use decorators to enhance services
- Testing models and services
If a controller is supposed to be lightweight and only concern itself with the view it’s controlling, what happens when you need functionality to be available to your entire application? If a controller should never communicate directly with other controllers, how do they share information? Whereas controllers are constrained to a specific context, AngularJS services exist to provide functionality that’s available to the entire application.
In this chapter we’ll explore what a service is and how to create a simple service. From there, we’ll show how to use services to communicate with a remote server and serve as a domain model for the entire application. After that we’ll dip our toes into some advanced functionality and see how to intercept remote server calls as well as decorate existing services. Figure 4.1 shows a high-level view of services.