Retrieving data from array services in Angular using Typescript

I need help retrieving data from an array in my services using a get function. I've tried using the .filter and .find functions, but I'm struggling with the execution and haven't been able to retrieve the data successfully. I know this may be a basic question, but I'm new to this and any assistance would be greatly appreciated.

tracker-data.ts:

export class TrackerData {
  entry?: number;
  exit?: number;
  clicks: string[] = [];
  url?: string;

  public get clickCount(): number
  { return this.clicks.length; }
}

tracker.service.ts

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

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

  public count = 0;

  constructor() { }

  addTrackerData(trackerData: TrackerData): void {
    this.websiteData.push(trackerData);
   }

   getData() {
      return this.websiteData;
   }
}

summary.component.ts (where the data should be displayed)

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 {
  websiteData: TrackerData[] = [];

  constructor(
    private trackerService: TrackerService,
  ) { }

  ngOnInit(): void {
  }

  getData(){
    this.websiteData = this.trackerService.getData();
    console.log(this.websiteData);
  }
}

Answer №1

The reason you are not seeing the data in the log is because the function is not being called anywhere in the code and is not being utilized in any of the lifecycle events. Typically, to initialize data from a service, functions from services are called in the ngOnInit lifecycle event. It seems like this is what you are attempting to do, so you should call the trackerService.getData() function there.

Here is an example of how you can do this:

ngOnInit(): void {
 this.websiteData = this.trackerService.getData();
    console.log(this.websiteData);
  }

While it is possible to call the function in the constructor (when the component is being created), this is not considered standard practice. Functions can also be triggered by events on your webpage, such as when a user clicks a button.

I recommend delving further into the Angular documentation as it provides thorough explanations of all the basics: https://angular.io/docs

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

What is the most effective way to iterate "from start to finish" through an array in C++?

When working with arrays in Python, you can compare each element with the "next" one, including comparing the last element with the first, using this code: a = [0, 1, 2, 3] for i in range(-1, 3): if a[i] + 1 >= a[i+1]: print a[i], &apos ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

Updating serialized data in PHP

I am seeking assistance with unserializing and updating the array values in PHP. My goal is to unserialize a string, update the value for a specific key while preserving the other values, and then reserialize the array. So far, my attempts have been unsucc ...

Extracting event handlers using @ContentChildren: A guide

I am dealing with a my-button component that needs to be enclosed within a my-button-row component in the following manner: <my-button-row> <my-button [label]="Some Label" (click)="func1($event)"></my-button> <my-button [label ...

Having trouble displaying the elements of an array using the map function in ReactJS?

Using the axios library, I am able to fetch data from the server and save it into an array called setCountries. This part of the process is functioning correctly. Link to code on codesandbox However, my goal is to display a list of country names that are ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

Navigating between child routes in an Angular2 component with two child routers is posing a challenge for me

I have a main component that sets up a Router pointing to 2 child components, each of which also has its own Router setup. Here's an example: Main Component import { Component } from '@angular/core'; import { RouteConfig, ROUTER_DIRECTIVES ...

Using Angular 7 shared service to allow sibling components to exchange data between each other

In my Angular 7 application, I have two sibling components - a configurator component and a custom stepper component. The configurator component is responsible for fetching data from the API and performing calculations on it. I would like to display the ca ...

Implement a check for the existence of a character in a string through the strstr() function in C

This particular issue seems to revolve around the use of the char data type and pointers. void main() { const char* a; char character = 65; a = &character; printf("%c \n", character); // OUTPUTS 'A' AS EXPECTE ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Validating forms in Angular 5 with the help of ngx-bootstrap

I am currently delving into Ari Lerner's ng-book about Angular 5. My setup includes ngx-bootstrap and Bootstrap 4. However, I am facing an issue with form validation that doesn't align with Mr. Lerner's implementation. I'm unsure whethe ...

Converting an array into a JavaScript Date object

I am currently working with an array of dates and looping through each element. The elements within the array are not date objects but rather strings, I believe. When I print each of the elements to the console, they appear as follows: 2015,09,19 2015,09, ...

How can Angular utilize dynamic InjectionTokens according to routes?

I am curious about the best way to initiate a service that relies on another service and a complex object used for creating a dependency within the service. Currently, I am utilizing an InjectionToken to inject the complex object into the service, but I re ...

What is the method to update reference models in mongodb by generating documents within a different model?

In my API, I have three models: Patient, Doctor, and Reviews. The Reviews model is referenced in the Doctor model, with the intention that a patient can post a review for a specific doctor using Review.create(). However, even after the review document is c ...

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

What is an elegant way to showcase a large 2D array in a WPF application, similar to the layout of Excel spreadsheet

Currently, I'm facing a challenge involving the display of a 2-dimensional array within a WPF window. The size of the array can reach up to 360*720 dimensions. Attempting to use a DataTable bound to a DataGrid proved to be inefficient, as it resulted ...

Using TypeScript to narrow down types within mapped types

Can you create a mapped type based on the property type? For example, if I want to map all properties with type String to Foo and all other types to Bar. Can this be done like this: type MappedType<T> = { [P in keyof T]: T[P] === String ? Foo : B ...