Reputation: 734
I developed a basic tracker that retrieves the time taken on each and every page of my website. The part that provides the time taken on each page works perfectly, but now I'm trying to add the time taken on each page in order to generate a total time taken throughout the whole use of the website.
tracker.service.ts - This retrieves the data
import { Injectable } from '@angular/core';
import { TrackerData } from '../modules/tracker-data';
@Injectable({
providedIn: 'root'
})
export class TrackerService {
websiteData: TrackerData[] = [];
public get count(): number
{
let count = 0;
this.websiteData.forEach(d => count += d.clickCount);
return count;
}
constructor() { }
addTrackerData(trackerData: TrackerData): void {
if (trackerData.url === undefined && this.websiteData.length > 0)
{
this.websiteData[this.websiteData.length - 1].clicks = trackerData.clicks;
return;
}
this.websiteData.push(trackerData);
}
getData() {
return this.websiteData;
}
}
summary.component.ts this retrieves the get data function from services in order to display the data
import { Component, OnInit } from '@angular/core';
import { TrackerService } from 'src/app/services/tracker.service';
import { TrackerData } from 'src/app/modules/tracker-data';
@Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.scss']
})
export class SummaryComponent implements OnInit {
public websiteData: TrackerData[] = [];
public clickCount = 0;
constructor(
private trackerService: TrackerService,
) { }
ngOnInit(): void
{
this.websiteData = this.trackerService.getData();
this.clickCount = this.trackerService.count;
}
}
summary.component.html - Here I show the information.
<h3>Task Summary</h3>
<div class="summary">
<p><span>{{ clickCount }}</span>Number of clicks</p>
<p><span>TOTAL TIME TAKEN</span></p> <!-- This is where I want to show the total time taken -->
</div>
<div *ngFor="let trackerData of websiteData">
<p>Page: {{ trackerData.url }}</p>
<p>Entry: {{ trackerData.entry | date: 'h:mm:ss:ms a' }}</p>
<p>Exit: {{ trackerData.exit | date: 'h:mm:ss:ms a' }}</p>
<p>Total time: {{ trackerData.exit - trackerData.entry | date: 'ss:ms' }}</p> <!-- This is what I want to add in order to retrieve the total time taken above -->
<p>Clicks: {{ trackerData.clickCount }}</p>
<ul>
<li *ngFor="let click of trackerData.clicks">{{ click }}</li>
</ul>
</div>
Upvotes: 1
Views: 275
Reputation: 4993
If you need the total time in all pages it would be convenient to create a function that calculates the total having the all data as the input.
total(websiteData):number {
return websiteData.reduce((acc, item)=>acc + (item.exit - item.entry), 0);
}
<p>Total time: {{ total(websiteData) | date: 'ss:ms' }}</p>
Upvotes: 1