Developer Snippet Diary

How to call HTTP API in angular using services


Below is a step-by-step explanation of your code, in a tutorial-style format:

Angular HttpClient: Making API Calls
In this tutorial, we are going to learn how to use Angular's HttpClient module to make HTTP requests in an Angular application. This module provides a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers.

Step 1: Importing the HTTP Module

First, we need to import the HttpClientModule into our application module. This allows us to inject the HttpClient service anywhere in our app.

// appendFile.modules.ts
import { HttpClient, HttpClientModule } from '@angular/common/http';
imports: [
  HttpClientModule,
],

Step 2: Creating a Service

Next, we'll create a service named ApiService which will handle all of our HTTP requests. We generate this service using the Angular CLI command ng generate service api.

In this service, we'll use the HttpClient service to create methods for each type of HTTP request: GET, POST, PUT, DELETE. These methods will accept a URL, a method type, and optionally some data to send with the request.

// api.service.ts
import { Injectable } from '@angular/common/http';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) { }
  callApi(url: string, method: string, data: any): Observable<any> {
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    let params = new HttpParams();

    switch (method) {
      case 'GET':
        return this.http.get<any>(url, { headers, params });
      case 'POST':
        return this.http.post<any>(url, data, { headers, params });
      case 'PUT':
        return this.http.put<any>(url, data, { headers, params });
      case 'DELETE':
        return this.http.delete<any>(url, { headers, params });
      default:
        return throwError('Invalid HTTP method');
    }
  }
  
}

Step 3: Using the Service in a Component

Finally, we're going to use our ApiService in a component. In this example, we'll use it in the MainComponent.

In the ngOnInit lifecycle hook, we'll call our callApi method and subscribe to the response. We'll log the response to the console, and also handle any errors that might occur.

// main.component.ts
export class MainComponent implements OnInit {

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    const url = 'https://dummyjson.com/products/1';
    const method = 'GET';
    const data = null;

    this.apiService.callApi(url, method, data).subscribe(
      (response) => {
        console.log(response); // Handle the response from the API
      },
      (error) => {
        console.error(error); // Handle any errors
      }
    );
  }
}

And that's it! You've successfully set up your Angular application to make HTTP requests using the HttpClient module. With this setup, you can easily make requests to any API from your Angular components.

Remember to replace 'https://dummyjson.com/products/1' with the actual API endpoint you want to hit, and adjust the HTTP method ('GET', 'POST', 'PUT', 'DELETE') and data as needed.

Posted by: R GONDAL
Email: rizikmw@gmail.com