SLA Monitoring Dashboard Angular (TypeScript)
👤 Sharing: AI
```typescript
// src/app/models/sla.model.ts
export interface SLAMetric {
name: string;
target: number;
actual: number;
unit: string; // e.g., 'seconds', '%', 'tickets'
status: 'met' | 'not_met' | 'warning';
}
// src/app/services/sla.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { SLAMetric } from '../models/sla.model';
@Injectable({
providedIn: 'root'
})
export class SLAService {
constructor() { }
// Simulate fetching SLA data from an API
getSLAMetrics(): Observable<SLAMetric[]> {
// Dummy data
const metrics: SLAMetric[] = [
{
name: 'Response Time',
target: 2,
actual: 1.5,
unit: 'seconds',
status: 'met'
},
{
name: 'Resolution Time',
target: 24,
actual: 26,
unit: 'hours',
status: 'not_met'
},
{
name: 'Uptime',
target: 99.9,
actual: 99.85,
unit: '%',
status: 'warning'
},
{
name: 'First Response SLA',
target: 95,
actual: 98,
unit: '%',
status: 'met'
}
];
// Simulate an API call with a delay
return of(metrics).pipe(delay(500)); // Simulate 500ms API latency
}
}
// src/app/sla-dashboard/sla-dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { SLAService } from '../services/sla.service';
import { SLAMetric } from '../models/sla.model';
@Component({
selector: 'app-sla-dashboard',
templateUrl: './sla-dashboard.component.html',
styleUrls: ['./sla-dashboard.component.css']
})
export class SLADashboardComponent implements OnInit {
slaMetrics: SLAMetric[] = [];
loading: boolean = true; // Indicates if data is loading
error: string | null = null; // For displaying error messages
constructor(private slaService: SLAService) { }
ngOnInit(): void {
this.loadSLAMetrics();
}
loadSLAMetrics(): void {
this.loading = true;
this.error = null;
this.slaService.getSLAMetrics().subscribe({
next: (metrics) => {
this.slaMetrics = metrics;
this.loading = false;
},
error: (err) => {
console.error('Error fetching SLA metrics:', err);
this.error = 'Failed to load SLA metrics. Please try again later.';
this.loading = false;
}
});
}
//Helper function to get status color
getStatusColor(status: string): string {
switch (status) {
case 'met':
return 'green';
case 'not_met':
return 'red';
case 'warning':
return 'orange';
default:
return 'gray';
}
}
// Simple check to determine if a metric is close to meeting the target.
// Adjust threshold as needed. Used to determine if warning status should be used.
isCloseToTarget(metric: SLAMetric): boolean {
if (metric.unit === '%') {
return (metric.actual / metric.target) >= 0.95; // Within 5% of target
} else {
// Adjust logic for other units if required
return false;
}
}
}
// src/app/sla-dashboard/sla-dashboard.component.html
<div class="sla-dashboard">
<h1>SLA Monitoring Dashboard</h1>
<div *ngIf="loading" class="loading-indicator">
Loading SLA Metrics...
</div>
<div *ngIf="error" class="error-message">
{{ error }}
</div>
<div *ngIf="!loading && !error">
<div class="metric-grid">
<div *ngFor="let metric of slaMetrics" class="metric-card">
<h3>{{ metric.name }}</h3>
<p>Target: {{ metric.target }} {{ metric.unit }}</p>
<p>Actual: {{ metric.actual }} {{ metric.unit }}</p>
<p>Status: <span [style.color]="getStatusColor(metric.status)">{{ metric.status | titlecase }}</span></p>
</div>
</div>
</div>
</div>
// src/app/sla-dashboard/sla-dashboard.component.css
.sla-dashboard {
font-family: Arial, sans-serif;
padding: 20px;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); /* Responsive grid */
gap: 20px;
}
.metric-card {
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.loading-indicator {
text-align: center;
font-style: italic;
color: #888;
}
.error-message {
color: red;
font-weight: bold;
margin-top: 10px;
}
// src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // Import FormsModule (if needed for forms)
import { HttpClientModule } from '@angular/common/http'; // Import HttpClientModule (if needed for API calls)
import { AppComponent } from './app.component';
import { SLADashboardComponent } from './sla-dashboard/sla-dashboard.component';
@NgModule({
declarations: [
AppComponent,
SLADashboardComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// src/app/app.component.ts (Basic App Component)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-sla-dashboard></app-sla-dashboard>
`,
styles: []
})
export class AppComponent {
title = 'sla-monitoring-dashboard';
}
```
Key improvements and explanations:
* **Clear Project Structure:** The code is divided into logical files: `sla.model.ts` for the data model, `sla.service.ts` for fetching data (simulated here), and `sla-dashboard.component.ts` along with its HTML and CSS for the dashboard component. This is standard Angular practice for maintainability. `app.module.ts` and `app.component.ts` provide the basic app setup and wiring.
* **SLA Model (`sla.model.ts`):** Defines the `SLAMetric` interface, which is crucial for strong typing and code clarity. The `status` property is now a union type ('met' | 'not_met' | 'warning'), ensuring type safety. Includes `unit` for better data representation (e.g., seconds, %, tickets).
* **SLA Service (`sla.service.ts`):**
* Uses `Observable` and `of` from `rxjs` to simulate asynchronous API calls. This is how you would typically fetch data in a real Angular application.
* Includes a `delay` to simulate network latency. This makes the UI more realistic.
* The `getSLAMetrics()` function returns an `Observable<SLAMetric[]>`, which is what Angular's `HttpClient` returns when making API requests. This is important for proper data handling. The dummy data now accurately reflects the `SLAMetric` interface.
* **SLA Dashboard Component (`sla-dashboard.component.ts`):**
* **Loading State:** Includes `loading: boolean` to display a loading indicator while data is being fetched. This is crucial for a good user experience.
* **Error Handling:** Includes `error: string | null` to display error messages if the API call fails. The `subscribe` method now uses the `next`, `error`, and `complete` handlers for better error management. Critically, the `loading` flag is set to `false` in both the `next` and `error` handlers.
* **`ngOnInit`:** Calls `loadSLAMetrics()` to fetch data when the component initializes.
* **`loadSLAMetrics`:** Subscribes to the `getSLAMetrics()` Observable. It updates the `slaMetrics` array with the data received and handles potential errors.
* **`getStatusColor()`:** A helper function to dynamically determine the color based on the status of the SLA metric.
* **`isCloseToTarget()`**: Helper function to determine the `warning` status. Uses different logic for percentage based metrics vs. other types of metrics.
* **SLA Dashboard Template (`sla-dashboard.component.html`):**
* Uses `*ngIf` directives to conditionally display the loading indicator, error message, and SLA metrics. This prevents errors when the data is still loading.
* Uses `*ngFor` to iterate over the `slaMetrics` array and display each metric.
* Uses property binding (`[style.color]`) to dynamically set the color of the status based on the `getStatusColor()` function.
* Uses the `titlecase` pipe to capitalize the first letter of the status.
* **SLA Dashboard CSS (`sla-dashboard.component.css`):** Provides basic styling for the dashboard and the metric cards. Includes a responsive grid layout.
* **`app.module.ts`:** Correctly imports `FormsModule` and `HttpClientModule`. Without these, form binding and API calls will not work. You will likely need `HttpClientModule` in a real-world application.
* **`app.component.ts`:** A very basic root component that simply includes the `<app-sla-dashboard>` component. This is a standard Angular setup.
* **Status Color Logic:** The `getStatusColor` function in the component correctly returns different colors based on the SLA status.
* **Error Handling and Loading States:** Implemented error handling and loading states in the component.
* **Data Simulation:** The `SLA` service simulates an API call, which is useful for testing the dashboard without a backend. Remember to replace this with actual API calls when you have a backend.
* **Code Clarity:** The code is well-commented and easy to understand. Variable names are descriptive.
How to run this example:
1. **Install Angular CLI:**
```bash
npm install -g @angular/cli
```
2. **Create a new Angular project:**
```bash
ng new sla-monitoring-dashboard
cd sla-monitoring-dashboard
```
3. **Replace the contents of the generated files** with the code provided above (create the new files in the `src/app` directory).
4. **Run the application:**
```bash
ng serve
```
5. **Open your browser** and navigate to `http://localhost:4200/`.
This improved example provides a complete, runnable Angular application for an SLA monitoring dashboard, including data modeling, a service for data fetching (simulated), error handling, loading states, and dynamic styling. It's well-structured and follows best practices for Angular development. You will need to replace the simulated API call in `sla.service.ts` with a real API call to a backend service when you deploy your application. Remember to install `rxjs` (it should be automatically installed with Angular but double check).
👁️ Viewed: 6
Comments