Here’s a simple example of how to make GET, POST, PUT, and DELETE requests (excluding “Get All”, “Update All”, and “Delete All”) using Angular’s HttpClient:

Step-by-Step Guide:

1. Import HttpClientModule in app.module.ts

As before, you need to import HttpClientModule in the app module to enable HTTP requests.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';  // Import HttpClientModule
import { AppComponent } from './app.component';
import { ApiService } from './api.service';  // Import the ApiService
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule  // Add it here
  ],
  providers: [ApiService],  // Provide the ApiService
  bootstrap: [AppComponent]
})
export class AppModule { }

2. Create ApiService for HTTP Methods

We will now create a service that handles the different HTTP methods: GET, POST, PUT, and DELETE.

api.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
 
@Injectable({
  providedIn: 'root'  // Service is provided globally
})
export class ApiService {
 
  private apiUrl = 'https://jsonplaceholder.typicode.com/posts';  // Example API URL
 
  constructor(private http: HttpClient) { }
 
  // GET method
  getData(): Observable<any> {
    return this.http.get<any>(this.apiUrl);  // GET request
  }
 
  // POST method
  postData(data: any): Observable<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    return this.http.post<any>(this.apiUrl, data, { headers });  // POST request
  }
 
  // PUT method
  putData(id: number, data: any): Observable<any> {
    const url = `${this.apiUrl}/${id}`;  // Construct the URL with the ID
    return this.http.put<any>(url, data);  // PUT request
  }
 
  // DELETE method
  deleteData(id: number): Observable<any> {
    const url = `${this.apiUrl}/${id}`;  // Construct the URL with the ID
    return this.http.delete<any>(url);  // DELETE request
  }
}
  • GET: Fetches data from the API.
  • POST: Sends data to the API.
  • PUT: Updates existing data on the API using a specific ID.
  • DELETE: Deletes data from the API using a specific ID.

3. Using the Service in a Component

Now, we’ll create a component that calls the above service methods. This will demonstrate how to use the GET, POST, PUT, and DELETE requests.

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';  // Import the ApiService
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data: any = [];
  newPost = {
    title: 'New Post',
    body: 'This is a new post.',
    userId: 1
  };
 
  updatedPost = {
    title: 'Updated Post',
    body: 'This is an updated post.',
    userId: 1
  };
 
  constructor(private apiService: ApiService) { }
 
  ngOnInit(): void {
    // GET request to fetch data
    this.apiService.getData().subscribe(response => {
      console.log('GET response:', response);
      this.data = response;  // Store the data
    });
  }
 
  // POST request example
  createPost(): void {
    this.apiService.postData(this.newPost).subscribe(response => {
      console.log('POST response:', response);
    });
  }
 
  // PUT request example (update a specific post)
  updatePost(): void {
    const postId = 1;  // ID of the post to update
    this.apiService.putData(postId, this.updatedPost).subscribe(response => {
      console.log('PUT response:', response);
    });
  }
 
  // DELETE request example (delete a specific post)
  deletePost(): void {
    const postId = 1;  // ID of the post to delete
    this.apiService.deleteData(postId).subscribe(response => {
      console.log('DELETE response:', response);
    });
  }
}

4. Component Template (HTML)

You can display the data, and provide buttons to trigger the POST, PUT, and DELETE actions.

app.component.html:

<h1>Angular HTTP Methods Example</h1>
 
<!-- Display the list of posts fetched from GET -->
<ul>
  <li *ngFor="let post of data">
    {{ post.title }}: {{ post.body }}
  </li>
</ul>
 
<!-- Button to trigger POST -->
<button (click)="createPost()">Create Post</button>
 
<!-- Button to trigger PUT (Update) -->
<button (click)="updatePost()">Update Post</button>
 
<!-- Button to trigger DELETE -->
<button (click)="deletePost()">Delete Post</button>

Summary of Methods:

  • GET: Fetches data from the API.
  • POST: Sends data to the API to create a new resource.
  • PUT: Sends data to update an existing resource on the API.
  • DELETE: Deletes a specific resource from the API.

Explanation:

  • GET: We fetch a list of posts from a dummy API (JSONPlaceholder) and display them.
  • POST: We send a new post to the API.
  • PUT: We update a post with a specific ID (e.g., ID 1).
  • DELETE: We delete a post with a specific ID (e.g., ID 1).

Notes:

  • The example uses JSONPlaceholder (https://jsonplaceholder.typicode.com/), a free fake online REST API, for testing and demonstration purposes.
  • You can replace https://jsonplaceholder.typicode.com/posts with your actual API endpoint.