We’ve all worked with Components and used component communication, but what do we do if we want to share data or logic across components?
WE BUILD SERVICES.
Let us try to understand what exactly services are.
So, a service is basically a class, but with a focused purpose. With services, the code becomes easy to test, debug, and reuse.
So the component that needs a service can use it in two ways:
1) Creating an instance of the service class
2) Registering the service in the module
If the component needs the services, the component class defines the service as a dependency. The Angular Injector then injects the service. This process is called Dependency Injection. It looks like this:
So, when a class receives the instances of objects that it needs from an external source rather than creating them itself, it is called Dependency Injection.
Steps to build a service:
1) Create a Service class
2) Use a decorator to define it
3) Import it
We have built a service, but remember our service is just a normal class unless we register it in the module.
Angular injects services with root injector(available to all the components) or with specific component injector(available to only that component and its child)
Let us register the service with the root injector like this:
This is how we can access this service from any component or any other service now.
In case, you want to access this service from only one component, this is how you do this.
In the product.component.ts,
For Injecting the service now, the angular injector uses a constructor to inject an instance of the class. Like this,
Now finally to use our service, let us call it.
And we are done creating our service and injecting it.