6 Services
This chapter covers
- Services and their role
- Creating many different types of services
- Using services to help retrieve and manage data
- Replacing logic from controllers with services
- Understanding how dependency injection works with services
In chapters 4-5, we had the Dashboard component, which generated some data for the rest of the application to consume. But that was only because we didn’t want to introduce more complexity into the example. This isn’t ideal in most scenarios, because that logic is hard to reuse and makes the component unnecessarily complex.
Your application will need to manage many tasks, and many of them will fall outside of the responsibility of components, such as managing data access, managing configuration across the app, and utility functions. The Angular HttpService is a great example of a service that makes it easy to reuse logic for making HTTP requests without having to implement it repeatedly. Although Angular and many libraries provide services for you to consume, you can and should make your own too.
Services are fundamentally JavaScript objects that provide commonly used logic in a way that other parts of the application can easily consume. For example, applications that require a user to log in will need to have a service to help manage the user’s state. Or you might have a service that helps manage how you make requests to your API and encapsulates the logic necessary away from the components using it.