Angular REST API Integration

This guide demonstrates how to fetch data from a REST API and display it in your Angular application. RESTful APIs are essential for interacting with backend services and retrieving or sending data.

Creating a Service to Fetch Data

Create a service to manage API calls. This ensures clean code separation and reuse across the application:

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

@Injectable({
    providedIn: 'root'
})
export class RestApiService {
    constructor(private http: HttpClient) {}

    getEventData(): Observable<any> {
    return this.http.get('assets/api/YourFileName.json'); // Example API endpoint
    }

    getDashboardEmailData(queryParams?: any): Observable<any> {
    let params = queryParams ? new HttpParams({ fromObject: queryParams }) : null;
    return this.http.get('assets/api/YourFileName.json', { params });
    }
}
Injecting the Service and Fetching Data

Use the service in a component to fetch data and store it locally for display. Implement the logic in the component's TypeScript file:

// src/app/index.component.ts
import { Component, OnInit } from '@angular/core';
import { RestApiService } from './services/rest-api.service';

@Component({
    selector: 'app-index',
    templateUrl: './index.component.html',
})
export class IndexComponent implements OnInit {
    displayedData: any[] = [];
    gridData: any[] = [];

    constructor(private restApiService: RestApiService) {}

    ngOnInit(): void {
    this.fetchEventData();
    }

    fetchEventData(): void {
    this.restApiService.getEventData().subscribe((data: any) => {
        this.gridData = data;
        this.displayedData = [...this.gridData];
    });
    }
}
            
API Call Example with Query Parameters

Here's an example of making an API call with query parameters:

// src/app/dashboard.component.ts
this.restApiService.getDashboardEmailData({ page: 1, limit: 10 }).subscribe((data: any) => {
    console.log('Dashboard Data:', data);
});
            
Displaying API Data in the Template

Use Angular's structural directives to display the fetched data in your component template:

<ng-container *ngIf="displayedData.length > 0">
<table>
<thead>
    <tr>
    <th>Event Name</th>
    <th>Date</th>
    <th>Location</th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let event of displayedData">
    <td></td>
    <td></td>
    <td></td>
    </tr>
</tbody>
</table>
</ng-container>
Handling Errors

Always handle API errors gracefully to improve the user experience:

this.restApiService.getEventData().subscribe({
    next: (data) => { this.displayedData = data; },
    error: (error) => { console.error('API Error:', error); }
});
            
Styling the Displayed Data

Customize the table and layout using CSS to ensure the data looks good on all screen sizes.

This setup demonstrates how to integrate a REST API in an Angular application and display the fetched data. You can further customize the API calls and display logic to meet your application requirements.

Receive the latest updates directly in your inbox!

Be the first to know about new updates and exclusive discounts. No spam, just great offers!

How about

A Custom Project?

With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.

Hire Us
Domiex Admin & Dashboards
230+

Total Pages

5+

Layouts

11+

Application

We provide quick support withing one business day to all of our customers.

© Domiex Created & Crafted by SRBThemes.