Angular / Angular HTTP and APIs

Making HTTP Requests with Angular

In this tutorial, we will explore how to make HTTP requests using Angular's HttpClient. We will cover the basic GET, POST, PUT, and DELETE requests.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores using Angular's HTTP client to make API requests and handle responses.

1. Introduction

In this tutorial, we will learn how to make HTTP requests using the HttpClient module in Angular. This module simplifies the process of making HTTP requests to your web server or API. We will specifically walk through how to send GET, POST, PUT, and DELETE requests, which correspond to the basic CRUD operations: Create, Read, Update, and Delete.

By the end of this tutorial, you will be able to:
- Understand how to use HttpClient in Angular.
- Make GET, POST, PUT, and DELETE requests.
- Handle HTTP responses.

The only prerequisite for this tutorial is basic knowledge of Angular and TypeScript.

2. Step-by-Step Guide

HttpClient is Angular's mechanism for communicating with a remote server over HTTP. To use HttpClient, we first need to import HttpClientModule in our AppModule (app.module.ts):

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

@NgModule({
  imports: [
    // other imports...
    HttpClientModule
  ],
})
export class AppModule { }

Next, we can import HttpClient in our component:

import { HttpClient } from '@angular/common/http';

Now, let's move on to making HTTP requests.

GET Request

A GET request is used to read or retrieve data from a server. Here's how to make a GET request:

this.http.get('http://api-url').subscribe(data => {
  console.log(data);
});

POST Request

A POST request is used to send data to the server:

this.http.post('http://api-url', { key1: 'value1', key2: 'value2' }).subscribe(data => {
  console.log(data);
});

PUT Request

A PUT request is used to update existing data on the server:

this.http.put('http://api-url', { key1: 'new-value1', key2: 'new-value2' }).subscribe(data => {
  console.log(data);
});

DELETE Request

A DELETE request is used to delete data from the server:

this.http.delete('http://api-url').subscribe(data => {
  console.log(data);
});

3. Code Examples

Let's look at an example that covers all these methods. We'll use a fake REST API called JSONPlaceholder in this example:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  getData() {
    // GET request
    this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(data => {
      console.log('GET Request is successful ', data);
    }, error => {
      console.log('Error', error);
    });
  }

  createData() {
    // POST request
    this.http.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    }).subscribe(data => {
      console.log('POST Request is successful ', data);
    }, error => {
      console.log('Error', error);
    });
  }

  updateData() {
    // PUT request
    this.http.put('https://jsonplaceholder.typicode.com/posts/1', {
      id: 1,
      title: 'foo',
      body: 'bar',
      userId: 1
    }).subscribe(data => {
      console.log('PUT Request is successful ', data);
    }, error => {
      console.log('Error', error);
    });
  }

  deleteData() {
    // DELETE request
    this.http.delete('https://jsonplaceholder.typicode.com/posts/1').subscribe(data => {
      console.log('DELETE Request is successful ', data);
    }, error => {
      console.log('Error', error);
    });
  }
}

4. Summary

In this tutorial, we have learned how to use Angular's HttpClient to make basic HTTP requests. We know how to send GET, POST, PUT, and DELETE requests and how to handle responses.

The next step would be to learn more about HttpClient, such as how to add headers to requests, how to handle errors, and how to make parallel requests.

5. Practice Exercises

  1. Create a new Angular project and set up HttpClient.
  2. Make a GET request to a fake API and display the data in your component.
  3. Improve your previous example by adding error handling.
  4. Make a POST request to the same API and display the response in your component.
  5. Make a PUT request to the API, update some data, and display the response.
  6. Finally, make a DELETE request.

Each exercise builds on the previous one, and by the end of them, you will have a solid understanding of how to use HttpClient in Angular. Remember, the key to mastering anything is practice!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help