Open In App

How to make an http call in angular

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

basicappfoderstructure

basicapp angular application

Dependencies:

"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:
http call in angular

How to make an http call in angular



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads