What is the process for creating a method within a class?

Here is the current structure of my class:

export class Patient {
    constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string,
                public trajectory: number, public vitalSigns: [GraphData[]], public latestReading: GraphData[]) {
    }

    public get combinedVSData(): Array<GraphData> {
        let combinedVitalSigns: GraphData[] = [];
        for (let data of this.vitalSigns) {
            combinedVitalSigns.push(data[0]);
        }
        return combinedVitalSigns;
    }
}

When attempting to call patient.combinedVSData, it returns undefined. I have tried returning a string instead with no success. Additionally, when adding console.log statements within the method, nothing is logged in the console, indicating that the method is not being called at all. What am I missing here?

The method is being called in one of my templates like this:

 [results]="patientService.patientLevel3.combinedVSData"

It is also being called in one of my components' classes for testing purposes:

onDrop(event: any){
let movedPatient: Patient = JSON.parse(event.dataTransfer.getData("patient"));
let from = parseInt(event.dataTransfer.getData("from"));

console.log(movedPatient.combinedVSData);

this.patientService.patientLevel3 = movedPatient;
this.patientService.removePatient(from, movedPatient.id);
}

}

In both cases, the result is returned as undefined.

UPDATE: Further investigation has revealed that the reason why combinedVSData is not present on the object is due to it being lost during the conversion to JSON. Unfortunately, I am unsure of what steps can be taken to address this issue.

Answer №1

Replace

public combinedVSData(): Array<GraphData>{}
with public get combinedVSData(): Array{

Answer №2

Instead of defining combinedVSData as a method, you should define it as a getter. I have provided an example to illustrate the distinction between using a getter and a method.

class Patient {
    constructor(public id: number) {
    }

    // Getter
    public get getId(): number {
        return this.id;
    }

    // Method
    public getIdMethod(): number {
        return this.id;
    }
}

const patient: Patient = new Patient(1);

console.log(patient.id);            // 1
console.log(patient.getId);         // 1
console.log(patient.getIdMethod);   // function () { return this.id; }
console.log(patient.getIdMethod()); // 1

console.log(patient);

https://i.sstatic.net/rV4Ww.png

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

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Creating a package exclusively for types on NPM: A step-by-step guide

I'm looking to set up a package (using either a monorepo or NPM) that specifically exports types, allowing me to easily import them into my project. However, I've run into some issues with my current approach. import type { MyType } from '@a ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...

The reason the CSS direct descendant selector does not affect Angular components

We are working with a basic main.html. <app> <sidebar></sidebar> <main-content> <router-outlet></router-outlet> </main-content> </app> After loading a component through routing (changing the ...

Design system styled component - "The type of X cannot be explicitly defined without a reference..."

How can I resolve this TypeScript issue? I have a styled component exported from a style.ts file and used in the index.tsx file of my React component: style.ts: import { styled, Theme } from '@mui/material/styles'; type CardProps = { theme? ...

Angular's input event fails to trigger for dynamically generated fields when pasted into them

When working with a form that has dynamically generated input fields, I encountered an issue. I needed to display a preview of the input contents on a div while pasting content into the fields. This project is built using Angular 11. Below is my .ts file: ...

Switching a parameter from a string to an object will cause Elasticsearch to be unable to properly index the new data structure

I have a collection of items stored in a Firebase database that I am using in conjunction with ElasticSearch for advanced queries. Recently, I had to update the structure of one of the items from a simple string, organizer: "some name", to a more complex ...

Customize Angular Material's Mat-Dialog background blur/darkening effect

Greetings, dear community members, I am currently utilizing angular along with angular material in my projects. By default, when a material dialog is opened, it slightly darkens the background. However, I am interested in having a blurred background inst ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

type of key extractor is unknown in React Native

How can I specify a type for the renderItem function of a FlatList in React Native? This is my current approach: // Importing the generic type for the FlatList render item function import { ListRenderItem } from "react-native"; // Assigning the ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

Converting JSON response from REST into a string format in Angular

I have developed a REST service in Angular that sends back JSON response. To perform pattern matching and value replacement, I require the response as a string. Currently, I am utilizing Angular 7 for this task. Below is an example of my service: getUIDa ...

The child component is receiving null input data from the Angular async pipe, despite the fact that the data is not null in the

I encountered a strange scenario that I'm unable to navigate through and understand how it occurred. So, I created a parent component called SiteComponent. Below is the TypeScript logic: ngOnInit(): void { this.subs.push( this.route.data.subscribe( ...

Using styled-components to enhance an existing component by adding a new prop for customization of styles

I am currently using styled-components to customize the styling of an existing component, specifically ToggleButton from material ui. However, I want my new component to include an additional property (hasMargin) that will control the style: import {Toggle ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Can I access the component attributes in Vuetify using Typescript?

For example, within a v-data-table component, the headers object contains a specific structure in the API: https://i.stack.imgur.com/4m8WA.png Is there a way to access this headers type in Typescript for reusability? Or do I have to define my own interfac ...

Error: The module '@angular/localize/init' could not be located within the specified directory '/usr/src/app/src'

After upgrading from Angular 8 to 9, I added the @angular/localize package. In my polyfill.ts file, I included the following import: import '@angular/localize/init'; When I compile and run my app locally in a browser, everything works fine. How ...