Developing a Dashboard Page and Accessing Stats API for an Expense and Income Tracking Project in Angular | Tutorial #18

Posted by

<!DOCTYPE html>

Creating Dashboard Page & Calling Stats API Call | Expense & Income Tracker Project in Angular | #18

Creating Dashboard Page & Calling Stats API Call

Welcome to the tutorial on creating a Dashboard page for our Expense & Income Tracker Project in Angular. In this tutorial, we will learn how to call an API to fetch stats data and display it on our dashboard page.

Step 1: Setting up the Dashboard Component

First, let’s create a new component called dashboard. Open the terminal and run the following command:

“`bash
ng generate component dashboard
“`

This command will create a new folder called dashboard in the src/app folder with all the necessary files for our dashboard component.

Step 2: Calling the Stats API

Next, let’s create a service to call the API that will fetch the stats data for our dashboard. Create a new file called stats.service.ts in the src/app/services folder and add the following code:

“`typescript
import { Injectable } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;

@Injectable({
providedIn: ‘root’
})
export class StatsService {

constructor(private http: HttpClient) { }

getStats() {
return this.http.get(‘https://api.example.com/stats’);
}
}
“`

Don’t forget to import and add this service to the providers array in the app.module.ts file.

Step 3: Displaying the Stats on Dashboard

Now, let’s update the dashboard.component.ts file to call the getStats method from the StatsService and display the data on the dashboard template.

“`typescript
import { Component, OnInit } from ‘@angular/core’;
import { StatsService } from ‘../services/stats.service’;

@Component({
selector: ‘app-dashboard’,
templateUrl: ‘./dashboard.component.html’,
styleUrls: [‘./dashboard.component.css’]
})
export class DashboardComponent implements OnInit {

stats: any;

constructor(private statsService: StatsService) { }

ngOnInit() {
this.statsService.getStats().subscribe((data) => {
this.stats = data;
});
}

}
“`

Finally, update the dashboard.component.html file to display the stats data on the dashboard page.

“`html

Total Expenses: {{stats.totalExpenses}}

Total Income: {{stats.totalIncome}}

Net Balance: {{stats.netBalance}}

“`

That’s it! You have successfully created the dashboard page and called the API to fetch the stats data for our Expense & Income Tracker Project in Angular. Now you can further customize the design and functionality of the dashboard as per your requirements.