In this blog, you will see how an HTTP request is sent to any API from Angular application.
I will demonstrate by sending an HTTP GET request to fetch some data from that REST API using HttpClient.
Before reading the blog further, if you have a little idea of Angular then it will be very good, else I would request you to read my previous blog on Angular.
As we all know that, Angular is mainly used for Client-Side application. Angular requires a service endpoint to communicate with data.
If you have an endpoint of a RESTful service, then that endpoint or URL can be used in Angular application in order to get data from a data source. A data source could be a SQL Server Database, an XML file, JSON file etc.
Let’s see how can we use an HTTP Get request from a basic Angular application.
To Call an API from Angular we need HttpClientModule which is available in ‘@angular/common/http’.
Read:- Angular Interview Questions
This HttpClientModule should be imported in the app.module.ts file. (Root App module)
Now we have to inject HttpClient in the component.ts file for which we have to call API.
What is HttpClient in Angular?
We all know that Angular is a client-side framework for data rendering. To communicate with backend services we will use the HTTP protocol.
HttpClient is available in ‘@angular/common/http’ and it offers a way to communicate with an API. HttpClient uses XMLHttpRequest that supports all the latest browsers to communicate with an endpoint.
HttpClient uses RxJS observables which allows the Angular app to handle asynchronous operations.
To Call API from Angular follow below steps
First, create an Angular project and add a component in it.
Import HttpClientModule in the app.module.ts file as shown below and then added in import array available in the root module file.
Below is the app.module.ts file source code.
I have created a component with name news, so injected HttpClient and then created an object of HttpClient in the constructor.
The object of HttpClient is client as shown in the below code.
Next, within ngOnInit() method, we have defined a const variable that will have the URL of the API.
As we have to fetch and show data on the page so we have used HttpClient.get() to call subscribe() method which fetch the records in a variable called response.
Once we have fetched the data from the API, we can either check on the console or we can store the response in a variable and then we can apply *ngFor on component’s HTML file to present data for users.
If you like this blog, then please share this on social media and comment down below to give your feedback.
Interview Questions and Answers Series –
Keep following – SharePointCafe.Net