You now have an understanding of how components represent views in Angular and how modules help us organize our components better and share responsibility. But we didn’t talk about where the data comes from in a component so you can display it.
Components only display the data in the template. They are not involved in getting the data from the backend. That is why we need something to bring our data to the component, and this is where Angular services come in.
If there is any shared data or shared logic that multiple components use, you can get that in a service, and that service then gives the data to your components. So basically, a service acts as the mode of communication between multiple components.
Why do we need services?
In Angular, we have components as the basic building blocks. We need some form of communication between components that are not related to each other, i.e. they are not the parent or child of the other component. Services allow such components to communicate and share data.
Creating a service in Angular
You can create a service using the CLI with the following command:
ng generate service <service-name>
ng g s <service-name>
This will create two files for you: