Let's Develop An Angular Application - Create An Angular Service To Access The Bike Details

This is the 10th article as part of my 'Let's develop an Angular application' article series.
 
So far, we have created an Angular application and a few components, created a model class for our Bike entity, and created an array of hard coded Bike details. Then, we have displayed the bike details from the hard coded array using ngFor. Also, we have installed and applied a few bootstrap classes to improve the UI. We created a navigation bar with dummy menus as well.
 
On clicking each bike tile, we have displayed the bike details in bike-details component.
 
At present, our bike rental portal application looks like the below screenshot.
 
image-portal
 
Please read my previous articles to get an idea about our application.
 
To read the previous article, click here >>  Display the bike details in bike details component
 
Next, we are going to implement Angular service in our application.
 
We will create an Angular service with name ‘DataService’. The purpose of this service is to manage the bike data.
 
We are not going to access the data from any APIs now. We will do that later.
 
We are going to move the hard coded bike details array from app component to the DataService and we will inject the DataService in to the app component to access the bike details array.
 
In short, we can list the today's work items as below.
  1. Create an Angular service ‘DataService’
  2. Move the bike details array from App component to DataService
  3. Access the bike details array in the DataService from App component using dependency injection.

What is an Angular Service?

 
As per the Angular style guide, we should limit the logic in a component to only that required for the view. All other logic should be delegated to services.
 
Angular service is a reusable piece of functionality shared across components.
 
Basically, it is just a class with @Injectable() decorator.
 
For example, we can create an a=Angular service with the below code.
  1. @Injectable()  
  2. export class TestService  
  3. {  
  4. }  
Then, we should provide an instance of the service in to the Angular Dependency Injection system.
 
For this, we can use the Provider array in the module file.
 
Providing the service class name in Provider array will let the angular dependency injection system know the other component or service may request an instance of the service.
 
One of the important points about Angular service is, it is singleton. Single instance is shared across all components.
 
Once the first instance is created, the Angular dependency injection system will cache it and deliver the same instance to the all components.
 
A service can be created when,
  1. The functionality is not required by view
  2. There is a need to share the logic to across multiple components
  3. There is a need to share the data across multiple components

Provide the Service into the Angular Dependency Injection system

 
There are two ways to provide the angular service in to the dependency injection system.
  1. Using the provider[] array in the module file.

    Eg: provider:[DataService] - here ‘DataService’ is the name of the class

  2. Inside @Injectable () decorator

    Eg,
    @Injectable({
    ProvidedIn: ‘root’
    })
The second method is advisable from Angular 6 onwards.
 
The main advantage of the second method is ‘Tree Shakable’ – ie, if the service is not used by any component or service, then the service will be removed from the code base. So the application only includes the codes that is need to our application to run.
 
Tree shakable feature is introduced in Angular 6.
 

Create a Data Service for our application

 
We can create an Angular service by using the angular cli.
 
The cli command to create the angular service is given below.
 
      ng generate service <Service-Name>
 
We can use the short hand command as well.
 
      ng g s <Service-Name>
      Eg : ng g s Data
 
By executing the above command, angular cli will create a ts file with name ‘data.service.ts’
 
Inside this file, we can find a class with name ‘DataService’ with @Injectable decorator.
 
Please refer to the the screenshot below:
 
image-create service
 
Here, I am creating the service inside ‘services’ folder.
 
Please refer to the data.service.ts content in below screenshot
 
image-data-service
 
As we can see in the @Injectable() decorator, by default angular using tree shaking provider to register the service to the root injector.
 

What is an Injector?

 
Here, we have created a class with name DataService. This class provides a service.
 
The @Injectable() decorator will marks it as a Service which can be injected to other components.
 
But, Angular can’t inject the service anywhere until we configure an Angular dependency injector with provider of the service.
 
The injector is responsible for the creation of the instance of the services and injecting them into the component classes. Angular is creating the injector for us when it executes the app and root injector is creates during the bootstrapping process.
 
image-injector
 
I think this is enough about Angular services.
 
Let’s move to our project
 
Since we have created the Data service already using angular cli, our first action item is created
 
Our next action item is move the bikeList array from app component to the Data service.
 
Copy the bike details array from the app component to the DataService class.
 
Then create method ‘getAllBikes()’ to return bikeList array.
 
Please refer to the screenshot below.
 
image-dataservice
 
Cool!
 
We have created an Angular service and created a method in it to return an array of elements.
 
Our second action item is also completed!
 
Next, we need to make changes in AppComponent class to access the data service.
 
The changes are,
  1. Implement the OnInit interface
  2. Delete the array elements – we are going to use the data service to access the bike list array
  3. Inject the DataService into the AppComponent class using ‘Constructor Injection
  4. Invoke the getAllBikes() method in the DataService and assign the bike details list into the local variable ‘bikeList’
Please refer to the screenshot to get a clear idea about the changes.
 
image-appcomponent
 
Success!
 
We have injected the DataServie in to our app component and retrieved the bike details array from DataSevice by calling the getAllBikes() method.
 
Check the browser, we will get the same result as before.
 

Conclusion

 
In this article, I have tried to explain about Angular service and its implementation.
 
We have created service and injected the service in to the AppComponent.
 
In my next article, we will see how to add a new bike details.
 
Happy Learning Create An Angular Service To Access The Bike Details


Similar Articles