Services in Angular
Let's take a closer look at the services and the best practices for writing services in Angular.
After this discussion on providers, it may be hard to see what role services provide in Angular. If we’ve learned that providers can provide data to our components and modules, why would we need services?
The role of services in Angular
Well, if providers give our application data and access to other modules and components, then services are where our application’s business logic happens.
Services make it easier to share the common functionality between the components.
The Angular framework doesn’t tell you that you have to use services, but the framework, through Dependency Injection, does make it extremely easy to write and consume services.
Example: Check username and password
We could write all the business logic of an application at the @Component
level. For example, a component could have a function that takes a username and password and makes an API to check that they are correct before allowing a user to log into the application.
This is fine, but what if we wanted to check the username and password somewhere else in the application? We would have to write the same code all over again in the new component that needs to check the login details.
Having a service that the components can delegate this logic to makes it easier to share common functionality ...