How to create an HTTP request in angular using HttpClient | E-commerce

HttpClient is used for fetching data from a server or local file.

Before you can use the HttpClient, you need to import the Angular HttpClientModule. Most apps do so in the root AppModule.

Add the below code in app.module.ts file

Code: app.module.ts(example)

import { NgModule }         from ‘@angular/core’;

import { BrowserModule }    from ‘@angular/platform-browser’;

import { HttpClientModule } from ‘@angular/common/http;

@NgModule({

  imports: [

    BrowserModule,

    // import HttpClientModule after BrowserModule.

    HttpClientModule,

  ],

  declarations: [

    AppComponent,

  ],

  bootstrap: [ AppComponent ]

})

export class AppModule {}

After adding HttpClientModule from @angular/common/http. Then create a service for get data from a server or local file.

For creating a service in angular, create a new folder called services and open the path in the terminal and type “ng g s product”.

G – define generate

S – define service

Product – the name of service

Then import HttpClient from ‘@angular/common/http’ to the service file.

Then import Observable from ‘rxjs’ as below code and creating a HTTP get method of product list from “productlist.json” file or you can use any API URL. 

example: https://example.com/api/productlist

Code:app/services/product.service.ts

import { Injectable } from ‘@angular/core’;

import { HttpClient } from ‘@angular/common/http’;

import { Observable } from ‘rxjs’;

@Injectable({

  providedIn: ‘root’

})

export class ProductService {

  constructor(private http: HttpClient) { }

  getProductList(): Observable<any> {

    return this.http.get(‘assets/dummy/productlist.json’);

  }

}

After creating services create dummy folder in the assets folder and create a file name productlist.json and paste the below code

Code:assets/dummy/productlist.json

{

    “status”:true,

    “productList”:[

        {

          “_id”: “5e804e29a915bb6a2297cfed”,

          “index”: 0,

          “price”: “$31.79”,

          “picture”: “/assets/image/Round-Neck-Wear-Tshirt.jpg”,

          “name”: “Duffy Houston”,

          “company”: “EQUITAX”,

          “stock”: 88

        },

        {

          “_id”: “5e804e29c0165da9c25fdf9c”,

          “index”: 1,

          “price”: “$32.92”,

          “picture”: “/assets/image/2.jpg”,

          “name”: “Sanford Stanley”,

          “company”: “ZILLA”,

          “stock”: 42

        },

        {

          “_id”: “5e804e29421be457e0764462”,

          “index”: 2,

          “price”: “$26.05”,

          “picture”: “/assets/image/3.jpg”,

          “name”: “Tracey Fleming”,

          “company”: “RODEMCO”,

          “stock”: 85

        },

        {

          “_id”: “5e804e296cd363835b6b1904”,

          “index”: 3,

          “price”: “$34.00”,

          “picture”: “/assets/image/4.jpg”,

          “name”: “Howe Ruiz”,

          “company”: “ARCTIQ”,

          “stock”: 27

        },

        {

          “_id”: “5e804e29f434203d0037bf41”,

          “index”: 4,

          “price”: “$14”,

          “picture”: “/assets/image/5.jpg”,

          “name”: “Powers Kaufman”,

          “company”: “EXOSPACE”,

          “stock”: 44

        },

        {

          “_id”: “5e804e295884556517418658”,

          “index”: 5,

          “price”: “$48.41”,

          “picture”: “/assets/image/6.jpg”,

          “name”: “Pugh Pierce”,

          “company”: “ZILPHUR”,

          “stock”: 64

        },

        {

          “_id”: “5e804e2940f3837a558497b9”,

          “index”: 6,

          “price”: “$27.59”,

          “picture”: “/assets/image/7.jpg”,

          “name”: “Fuentes Booth”,

          “company”: “MANUFACT”,

          “stock”: 23

        }

      ]

}

Go to product.component.ts file and import productService from ‘product.service.ts’ file

Then call the service function from here. Before we call the service from the constructor itself. It will be called simultaneously to the product component.

See the below Code: product.component.ts

import { Component, OnInit } from ‘@angular/core’;

import { ProductService } from ‘../services/product.service’;

@Component({

  selector: ‘app-products’,

  templateUrl: ‘./products.component.html’,

  styleUrls: [‘./products.component.css’]

})

export class ProductsComponent implements OnInit {

  public data;

  constructor(private prodService : ProductService) { }

  ngOnInit(): void {

   this.prodService.getProductList().subscribe(resp=>{

    this.data = resp;

    console.log(resp.status);

 },error=>{});

}

}

Then make a public variable data and append the resp to the data.

Below code of product.component.html

<div class=“container-fluid mt-5 pt-5”>

  <div class=“row”>

    <div class=“col-12”>

      <h6 class=“text-left”>Men’s wear</h6>

    </div>

  </div>

<div class=“row”>

    <div class=“col-sm-6 col-md-3 col-xs-12 col-12 mb-4 “ *ngFor=‘let prod of data?.productList’>

    <div class=“card” >

      <i class=“fa fa-heart-o fav”></i>

        <img class=“card-img-top “ style=“height:220px” src=“{{prod.picture}}” alt=“Card image cap”>

        <div class=“card-body “ style=“background-color: #f9f9f9;”>

          <h6 class=“card-title text-left “>{{prod.name}}</h6>

          <p class=“card-text text-left  mb-0”>Price: <span class=“font-weight-bold float-right text-success”>{{prod.price}}</span></p>

          <p class=“card-text text-left “>Stock left: <span class=“font-weight-bold float-right text-danger”>{{prod.stock}}</span></p>

        </div>

      </div> 

    </div>

</div>

</div>

Lets run the project by using command ng serve. Then go to the localhost:4200

One thought on “How to create an HTTP request in angular using HttpClient | E-commerce”

Leave a Reply

Your email address will not be published. Required fields are marked *