How to API call in Angular step by step guide

how-to-call-api-in-angular-step-by-step-guide

In Angular, you can use the Angular HttpClient module to make HTTP requests to APIs. Here’s a step-by-step guide on how to call an API in Angular:

Step 1: Import HttpClientModule

Make sure that you have the HttpClientModule imported in your Angular application. You can do this by adding it to the imports array in your AppModule or any other module where you want to use it.

// src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Step 2: Create a Service to Handle API Calls

Create a service that will handle your API calls. Use the Angular CLI to generate a service:

ng generate service my-api

This will create a ‘my-api.service.ts’ file. Open it and define your API calls.

// src/app/my-api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class MyApiService {
  private apiUrl = 'https://api.example.com'; // replace with your API endpoint

  constructor(private http: HttpClient) {}

  getSomeData(): Observable {
    return this.http.get(`${this.apiUrl}/some-endpoint`);
  }

  postData(data: any): Observable {
    return this.http.post(`${this.apiUrl}/some-endpoint`, data);
  }
}

Step 3: Inject the Service into a Component

Now, inject your service into a component where you want to use the API data.

// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { MyApiService } from './my-api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  constructor(private myApiService: MyApiService) {}

  ngOnInit() {
    this.fetchData();
  }

  fetchData() {
    this.myApiService.getSomeData().subscribe(
      (data) => {
        console.log('API Data:', data);
        // Process the data as needed
      },
      (error) => {
        console.error('Error fetching data:', error);
      }
    );
  }

  postData() {
    const dataToSend = { /* Your data object */ };
    
    this.myApiService.postData(dataToSend).subscribe(
      (response) => {
        console.log('API Response:', response);
        // Process the response as needed
      },
      (error) => {
        console.error('Error posting data:', error);
      }
    );
  }
}

Step 4: Use the Component in Your Template

You can now use your component in your template to display data or trigger API calls.


API Data

Step 5: Run Your Application

Run your Angular application using:

ng serve

Visit http://localhost:4200 in your browser, and you should see your component rendering and making API calls as expected.

Related Posts