Member-only story
How to create a data service in Angular 9
In this example, I will walk you through how to properly create a service that can be shared among all of your components inside your angular application relying on Angular dependency injection to inject it into the desired component constructor.
Why use a service?
As a general rule and a good practice we must keep components in Angular lean. In other words components should not perform any business logic nor should they directly perform CRUD (Create, Read, Update and Delete) operations. A Component main responsibility is to focus on presenting data to the view and delegate complex logic and heavy operations to services.
Services have great benefits in object oriented programming. Services are great for sharing information among classes that do not know each other. In other words, if I have three components that need to use the same logic, it would be counterproductive to create the same logic in each component. This is a recipe for disaster as it creates a lot of overhead to maintain three sets of code that perform the same work. Instead, we can create a service, add a function inside the service that perform the logic needed in all three components, inject the service into each component and reference the function in each component when needing to use it.