You are currently viewing Fetching Data from an API in Angular Using a Service Class

We’ll build an Angular app that fetches data from a mock API and displays it in a component.
We’ll use:

  • Service for API requests
  • Component to consume the service
  • Template binding to show the data
  • Two example APIs: Employees and Books

1. Setup

PowerShell
npm install -g @angular/cli
ng new api-demo --routing=false --style=css
cd api-demo
ng serve

2. Create the Service

We’ll make one service (data.service.ts) to handle multiple API calls.

PowerShell
ng generate service services/data

src/app/services/data.service.ts

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

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

  private employeesUrl = 'https://dummyjson.com/users';
  private booksUrl = 'https://openlibrary.org/subjects/love.json?limit=5';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<any> {
    return this.http.get(this.employeesUrl);
  }

  getBooks(): Observable<any> {
    return this.http.get(this.booksUrl);
  }
}

Here we store our API endpoints in private variables, making them easy to change later.


3. Enable HTTP in Angular

Make sure to import HttpClientModule.

src/app/app.module.ts

TypeScript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';
import { BookComponent } from './book/book.component';

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

4. Create Components

PowerShell
ng generate component employee
ng generate component book

5. Employee Component

src/app/employee/employee.component.ts

TypeScript
import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  employees: any[] = [];
  loading = true;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getEmployees().subscribe({
      next: (data) => {
        this.employees = data.users; // API specific
        this.loading = false;
      },
      error: (err) => {
        console.error('Error fetching employees:', err);
        this.loading = false;
      }
    });
  }
}

src/app/employee/employee.component.html

HTML
<h2>Employee List</h2>
<div *ngIf="loading">Loading...</div>
<ul *ngIf="!loading">
  <li *ngFor="let emp of employees">
    {{ emp.firstName }} {{ emp.lastName }} - {{ emp.email }}
  </li>
</ul>

6. Book Component

src/app/book/book.component.ts

TypeScript
import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
  books: any[] = [];
  loading = true;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getBooks().subscribe({
      next: (data) => {
        this.books = data.works; // API specific
        this.loading = false;
      },
      error: (err) => {
        console.error('Error fetching books:', err);
        this.loading = false;
      }
    });
  }
}

src/app/book/book.component.html

HTML
<h2>Book List</h2>
<div *ngIf="loading">Loading...</div>
<ul *ngIf="!loading">
  <li *ngFor="let book of books">
    {{ book.title }} by {{ book.authors[0]?.name }}
  </li>
</ul>

7. App Root Template

src/app/app.component.html

HTML
<h1>API Data Fetch Demo</h1>
<hr>
<app-employee></app-employee>
<hr>
<app-book></app-book>

8. Run

PowerShell
ng serve

Open http://localhost:4200
You’ll see two lists — one for employees and one for books — fetched from different APIs using a shared service.


How It Works

  1. DataService holds all API methods
  2. HttpClientModule enables HTTP in Angular
  3. Each component calls the appropriate method from the service
  4. Async subscription updates the template when data arrives
  5. The template uses *ngFor to loop and display items
Please follow and like us:

Leave a Reply