How to make an http call in angular
Last Updated :
17 Apr, 2024
Angular, with its robust framework and extensive ecosystem, offers you powerful tools for building modern web applications. One such tool is the HttpClient
module, which provides a seamless way to make HTTP calls and interact with RESTful APIs or backend services. In this article, we'll explore making HTTP calls in Angular, using the capabilities of the HttpClient
module to fetch data, handle responses, and manage requests effectively.
Prerequisites
Approach
- Import HttpClientModule: Import
HttpClientModule
in the root module of your Angular application to enable HTTP services. - Inject HttpClient Service: Inject the
HttpClient
service into your components or services where you want to make HTTP requests. - Make the HTTP Request: Use the methods provided by the
HttpClient
service (get
, post
, put
, delete
, etc.) to make the HTTP request. - Handle the Response: Subscribe to the observable returned by the HTTP method to handle the response asynchronously.
- Error Handling: Handle errors by providing a second callback function to the
subscribe
method.
Steps to make an HTTP call in Angular
Step 1: Create an Angular application using the following command
ng new basicapp
Step 2: After creating your project folder i.e. basicapp, move to it using the following command:
cd basicapp
Folder Structure:
basicapp angular applicationDependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Code Example:
HTML
<!-- app.component.html -->
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Price</th>
<th>Rate</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of products">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
<td>{{item.price}}</td>
<td>{{item.rating.rate}}</td>
<td><img src={{item.image}} alt={{item.title}} /></td>
</tr>
</tbody>
<p>{{error}}</p>
</table>
</div>
JavaScript
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
AppRoutingModule,
HttpClientModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
JavaScript
//app.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, catchError } from 'rxjs';
import { BASEURL, Iproducts } from './utils';
@Injectable()
export class AppService {
private http = inject(HttpClient);
fetchData(): Observable<Iproducts[]> {
return this.http.get<Iproducts[]>(BASEURL).pipe(
catchError((error) => {
throw error.message;
})
);
}
}
JavaScript
//app.component.ts
import { Component, OnInit, inject } from '@angular/core';
import { AppService } from './app.service';
import { Iproducts } from './utils';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService],
})
export class AppComponent implements OnInit {
private appservice = inject(AppService);
products: Iproducts[] = [];
error = '';
ngOnInit(): void {
this.appservice.fetchData().pipe(
map((products) => products.slice(0, 8))
).subscribe({
next: (response) => {
this.products = response;
},
error: (error) => {
this.error = error;
},
});
}
}
JavaScript
//utils.ts
export const BASEURL = 'https://fakestoreapi.com/products';
export interface Iproducts {
id: number;
title: string;
price: number;
description: string;
category: string;
image: string;
rating: {
rate: number;
count: number;
};
}
To start the application run the following command.
ng serve
Output:
How to make an http call in angular
Similar Reads
How to cancel an $http request in AngularJS ? In AngularJS, we use different sources to fetch the data as per our needs. We call different data source APIs using $http requests. We can fetch the data along with cancelling the real-time running request. In AngularJS, we can use the $q service along with the promises to cancel the request. Also,
4 min read
How to call an AngularJS Function inside HTML ? A Function is a set of statements that takes input, does some specific computation, and produces output. In this article, we will learn How to Call an AngularJS function inside HTML. To achieve this, we can use {{...}} to call the function from HTML. We can also pass arguments and return the result
3 min read
How to Enable HTML 5 Mode in Angular 1.x ? HTML5 mode in Angular1.x is the configuration that replaces the default hash-based URLs and provides more user-friendly URLs using the HTML5 History API. This feature mainly enhances our one-page application and also provides a better experience to the users. We need to configure our server with pro
6 min read
Make HTTP requests in Angular? In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It's like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP request
4 min read
How to Create a new module in Angular ? Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read