Angular services are singleton object that gets instantiated only once in a lifetime of an application.
Consider our application having following components
Let's say we want to log some data in AboutComponent and UserDetailComponent.
Both logs are same, so basically we are duplicating code in two different components.
Suppose in User component we also want to access some data, and we don't know if we will use it in other part of application.
So use cases for services are
To avoid duplication of code
Data Storage
Communication between components
A service is just another class which acts as a central repository, as a central buisness unit where you can centralize your code.
Here in this case we can make logService to centralize it .
How to create a service
- simply run the command in your terminal
*here g means generate ,s means service *
here you see we have made one class with service name
As I have mentioned in my earlier blogs
This means your service can be accessed from anywhere throughout the application .
How to access the service in your component
- First you will declare a property stateService of type MyStateService(i.e your service class)
-Make sure to import the service at the top
- Now you can directly call your method present in service through property like this
If you don't use "@Injectable({providedIn:'root'})" in your service . In that case you have to provide a service in providers array of component in which you're trying to inject a service.
Like this you will have to do it,
It is not recommended , however you can use it acc to your requirement.
Hierarchical Injector
Angular dependency injector is actually a hierarchical Injector.
It means if you provide a service in one component then angular framework knows how to create service instance for this component and all of it's child component.
**
**All component will receive same instance of service because it is singleton.
It is top to bottom approach.
Thanks for reading,hope it is helpful
Please like share and follow for more such content
Top comments (0)