Exploring Angular Services
Services in Angular is meant for specifically making the call to RestFul API and getting the data and passing data to all component whichever component subscribe to it. Moreover, it gives us the benefit of code reusability and data sharing across components.
Goals
How to create a basic service in Angular
How to subscribe to the service response.
How to handle errors in service.
Specifications
In this tutorial, we will create a basic angular application and try to use the service to get data and pass the data component.
Why Services
The component is meant for providing the data to view, when I say view means providing the data to respective HTML whatever is required, it is not a good practice to make an API call directly from the component. Services give the benefit of separation of concerns and you can say single responsibility principle as well.
Let's see services in action
Create an angular project: go to VS code integrated terminal
Run - ng new ServiesTest
Run this newly created project by using the below command
ng serve
Once you run this command you must see the below page at http://localhost:4200/
Create a service by using the below command
ng g s DateTime
Now go to the DateTimeService.ts file you will find below the code
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DateTimeService {
constructor() { }
}
If you notice it has the @Injectable decorator similar to the @Component decorator which we use to have in an angular component. @Injectable means it can participate in dependency injection, those who don't know dependency injection I will explain it in my next article as it is not the topic of this discussion, it needs further explanation, so will keep that in a separate article.@Injectable accepts metadata objects. So here you can provided In value as root, which means this service can be injected in any of the classes across the project.
Now let us write the code to consume the actual service. So here I am trying to call a real-time RestFul API which is fromhttps://www.jsontest.com/
We will call an API located at : http://date.jsontest.com So here is the code for the same :
So my code is complaining about httpClient, map, catchError, and errorHandler.
So let us do the import for these complaints.
import { HttpClient } from '@angular/common/http';