How To Make API Calls In Angular Applications

Introduction

Making API calls is a common task in Angular applications, and it can be achieved using Angular's built-in HttpClient service. Here are the steps to make API calls in Angular.

Step 1. Import the HttpClient module

 You need to import the HttpClientModule in your app.module.ts file.

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

Step 2. Create a service

Create a new service to handle the HTTP requests. In this service, you can create methods to handle different types of requests (GET, POST, PUT, DELETE, etc.). Here's an example of a service.

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

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

  apiUrl = 'https://jsonplaceholder.typicode.com';

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any[]> {
    return this.http.get<any[]>(`${this.apiUrl}/posts`);
  }

  getPostById(id: number): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/posts/${id}`);
  }

  addPost(post: any): Observable<any> {
    return this.http.post<any>(`${this.apiUrl}/posts`, post);
  }

  updatePost(id: number, post: any): Observable<any> {
    return this.http.put<any>(`${this.apiUrl}/posts/${id}`, post);
  }

  deletePost(id: number): Observable<any> {
    return this.http.delete<any>(`${this.apiUrl}/posts/${id}`);
  }
}

Step 3. Inject the service

Inject the ApiService into your component or another service where you want to use it. You can do this by adding it to the constructor of your component or service.

import { Component } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let post of posts">{{ post.title }}</li>
    </ul>
  `,
})
export class AppComponent {

  posts: any[];

  constructor(private apiService: ApiService) {}

  ngOnInit() {
    this.apiService.getPosts().subscribe((data: any[]) => {
      this.posts = data;
    });
  }
}

Step 4. Use the methods

Use the methods defined in the service to make the API calls. In the example above, we are using the getPosts() method to get a list of posts from the API and display them in a list.

That's it! With these steps, you can make API calls in your Angular application.