Adding a timestamp to an array in Angular/Typescript services

I've been struggling with adding a timestamp OnInnit to track the time a user visited a page. I want to include the timestamp in an array within my services, but I keep encountering errors and can't seem to figure it out on my own. Any assistance would be greatly appreciated.

tracker-data.ts

export class TrackerData {
  entry?: number;
  exit?: number;
  clicks?: number;
  url?: string;
}

tracker.service.ts

import { Injectable } from '@angular/core';
import { TrackerData } from '../modules/tracker-data';

@Injectable({
  providedIn: 'root'
})
export class TrackerService {
  trackerData: TrackerData;
  websiteData: TrackerData[];

  public entryTime: {entry: number} [] = [];

  constructor() { }

}

tracker.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { TrackerService } from '../services/tracker.service';
import { TrackerData } from '../modules/tracker-data';

@Component({
  selector: 'app-tracker',
  templateUrl: './tracker.component.html',
  styleUrls: ['./tracker.component.scss']
})
export class TrackerComponent implements OnInit, OnDestroy {

  constructor(
    public trackerService: TrackerService,
    private websiteData: TrackerData[]
    ) { }


  ngOnInit(): void {
    const timeOfEntry = Date.now();
    this.websiteData.push(timeOfEntry); // Type 'number' has no properties in common with type 'TrackerData'.
  }

Although the code above may not be perfect, I am new to this and doing my best to learn.

Answer №1

The issue here is quite straightforward: you are attempting to include a date (the timestamp) as an object of type TrackerData, which is not the correct approach. Instead, you should first instantiate an object of the TrackerData class and then assign the timestamp value accordingly.

const trackerData = new TrackerData(); // Instantiate the object
trackerData.entry = Date.now(); // Assign the entry timestamp
this.websiteData.push(trackerData); // Add it to the array

Answer №2

export class WebData {
  arrival?: number;
  departure?: number;
  interactions?: number = 0;
  location?: string;
}
import { Injectable } from '@angular/core';
import { WebData } from '../modules/web-data';

@Injectable({
  providedIn: 'root'
})
export class WebService {
  siteData: WebData[];
  constructor() { }

  addWebData(webData: WebData): void {
   this.siteData.push(webData);
   //store data in cache or server for retention
  }
}
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebService } from '../services/web.service';
import { WebData } from '../modules/web-data';
import { Router } from '@angular/router';

@Component({
  selector: 'app-web-tracker',
  templateUrl: './web-tracker.component.html',
  styleUrls: ['./web-tracker.component.scss']
})
export class WebTrackerComponent implements OnInit, OnDestroy {
  private pageDetails: WebData = new WebData();
  constructor(
    private webService: WebService,
    private router: Router
    ) { }

  @HostListener('click', ['$event.target'])
  onClick(btn) {
    this.pageDetails.interactions++;
  }

  ngOnInit(): void {
    this.pageDetails.arrival = Date.now();
    this.pageDetails.location= this.router.url;
  }

  ngOnDestroy(): void {
    this.pageDetails.departure = Date.now();
    this.webService.addWebData(this.pageDetails);
  }

This implementation captures basic data. For data persistence on page refresh, consider storing information in the cache.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging environment variables in template documents

Can you incorporate environment variables into template files successfully? Currently, I am experimenting with the following syntax: <img class="preview-image" src="{{environment.assets + item.image}}" /> However, this approach leads to the follow ...

Tips for executing the JetBrains WebStorm refactoring tool 'modify ES6 import' for an entire project

Following a project refactor, certain files were relocated to a different npm package, leading to changes in source files to re-export them from their new location (in order to streamline the migration process). Later on, I came across a helpful refactori ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

Issue: Unable to assign type 'FormDataEntryValue' to type 'string'. Type 'File' cannot be assigned to type 'string'

After retrieving data from the formData, I need to pass it to a function for sending an email. Error: The error message states that 'FormDataEntryValue' is not compatible with type 'string | null'.ts(2322) definitions.ts(119, 3): The e ...

Transform an array containing arrays into an array of individual objects

After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes. The ...

Leverage Prisma's auto-generated types as the input type for functions

Exploring the capabilities of Prisma ORM has led me to experiment with creating models and generating the PrismaClient. Initially, I thought it would be possible to utilize the generated types for variables and response types, but that doesn't seem to ...

PHP Unleashed: Unraveling the Mysteries

What is the Best Way to Extract Data from This Array? I Need to display the First Object of My Array, Specifically the id field in the 3rd Row. <?php $con=mysqli_connect("localhost","root","","arrayy"); // Check connection if (mysqli_conne ...

What factors contribute to 'tslib' having more downloads than 'typecrypt'?

How is it possible that 'tslib', a library for 'typescript', has more downloads than 'typescript' itself? If one does not use 'typescript', then they cannot utilize 'tslib' as well. Just because someone us ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Angular application experiencing issues with loading React web component: encountering error when attempting to search for 'adoptedCallback' using 'in' operator with undefined value

I recently created a basic web component using React import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> He ...

Angular component causing style disruptions

As a newcomer to Angular, I am currently in the process of converting my previous project from .net to angular. However, I have encountered an issue that is specifically related to Angular, so please forgive me if it seems trivial. I am facing difficulti ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Having trouble with Angular redirecting to the incorrect URL?

Currently delving into the world of Angular, I am eager to create a straightforward application where users can effortlessly switch between two components. The issue arises when attempting to navigate back from the navbar to the login component: <a rout ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

What is the best way to apply a CSS class to a ComponentRef that has been generated in Angular 5

I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef and ComponentFactoryResolver. My goal is to determine the class based on which other Components have already been added to myViewContainerR ...

What is the best way to retrieve a value from an array of objects containing both objects and strings in TypeScript?

Consider this scenario with an array: const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; The goal is to access the value of 'second&ap ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

PHP unset() having issues with selective removal

I have come across various unset() issues on this platform, but the one I am facing is unique. My goal is to create an array that excludes certain file names from a directory listing, specifically ".", "..", "feed.txt", and "index.php". Below is the code s ...