Making HTTP Requests with Angular

Tutorial 1 of 5

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!