What causes the return of 'undefined' when trying to access properties of a TypeScript object in an Angular 2 application?

I have been working on an angular2 project where I am utilizing the http module to send a GET request. The server responds with an object that seems to be deserialized correctly into its corresponding TypeScript object. However, when I attempt to access a property from this object, it returns undefined. Strangely, when I check the console right before accessing these properties, the data is clearly present.

Below is how my getDataForEmployee method looks like:

  getDataForEmployee(data){
    var url = this.active+"/guest/"+data;

    var headers = new Headers();

    headers.append("Content-Type", "application/json");

    return this.http
      .get(url, {headers:headers})
      .toPromise()
      .then((res:Response)=> res.json() as Employee);

  }

This is the method responsible for handling the response:

this.employeeHttp.getDataForEmployee(userid)
  .then((employee:Employee)=>{
    console.log(employee);
    console.log("firstname: "+employee.firstName);
    ...

Here is the structure of the Employee class:

 export class Employee {

    ...
      private _firstName:string;
    ...

      get firstName(): string {
        return this._firstName;
      }

      set firstName(value: string) {
        this._firstName = value;
      }

    ...
    }

The screenshot displays the console output during this request. https://i.sstatic.net/7VVbd.png

I am puzzled as to why the firstName property returns undefined even though it exists in the object moments before. Any insights into this issue would be greatly appreciated.

Answer №1

The desired outcome can only be achieved through inheritance. Simply declaring an object as a class does not automatically make it inherit the class, meaning that `employee` is not considered a child of `Employee` in your current code.

In order to call the getter, you must first inherit it. For example:

let emp = new Employee("Dan"); // passing only firstName for demonstration

Afterwards, you will be able to access `emp.firstName`, which should return `Dan`. Ensure that your `Employee` class also accepts arguments.

I have provided a plunker demo where the `Employee` class takes one argument for firstName. Make sure to keep your developer tools open to observe both the getter and setter in action.

Since TypeScript only checks code during compile time, there's no way to verify if the API returns something different (e.g. `_name`) instead of `_firstName` at runtime. Therefore, I suggest utilizing an `interface` instead of a `class` in this scenario.

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

Showing collections of items in a Kendo Grid column

I am tasked with presenting data in a grid format where the entire array needs to be displayed in one column. To illustrate, let's consider a basic example using the following data structure: export class Person { public Name: string; public ...

Failure of VSCode breakpoints to function properly with TypeScript npm linked package

I am developing a Next.js app using TypeScript and my .tsconfig file includes the following configurations: { "compilerOptions": { "baseUrl": "src", "experimentalDecorators": true, "target": & ...

React router loader is not functioning correctly when trying to fetch data

My attempt to fetch an array of data from an API is resulting in an empty response within the application. However, when I try the same call in a swagger, it returns the correct array. HomePage.tsx: const HomePage = () => { const books = useLoaderDat ...

How come the Handsontable CSS styles are not being used on my Angular frontend?

I am currently facing an issue while trying to integrate a Handsontable into my Angular frontend. I was able to successfully implement the basic example from in a new Angular project. However, when I tried to add the exact same code to my existing reposit ...

Guide to Implementing Kendo-Grid in Angular 4 CLI

Having trouble using the Kendo-Grid in Angular4? You may encounter this error message: Uncaught Error: Template parse errors: 'Kunden-grid' is not a known element: 1. If 'Kunden-grid' is an Angular component, then verify that it is par ...

Angular / ThreeJS - "error: scene is not defined"

I recently started exploring ThreeJS and wanted to load an .obj file using the OBJLoader feature of ThreeJS. However, I encountered an error Cannot read property 'scene' of undefined This error occurred at the line this.scene.add( object ); ...

Having trouble understanding JSON and Arrays in TypeScript

When extracting data from the database using Sveltekit and Node.js, I always fetch data in the following way: ... responseData = await response.json(); The retrieved data is an Object, which can be assigned to an array like this: let getData = []; getData ...

Leverage JSON to produce an output with EventEmitter

The title captures the essence of my query perfectly. I am curious if there is a method to produce an output eventemitter through JSON in Angular, allowing me to receive specific events and perform additional tasks externally. ...

Implementing ngClass change on click within an Angular component using Jasmine: A comprehensive guide

It seems like the click event is not triggering and the ngClass is not changing to active on the button I am attempting to click. -- HTML: <div class='btn-group' role='group' aria-label=""> <button type='button&apos ...

I need guidance on retrieving items from the useRouter() hook when utilizing Next.js with the App Router approach

This code snippet demonstrates how to use Pages Router in React import { useRouter } from "next/router"; import React from "react"; function ShowroomListings({}) { const router = useRouter(); const { listingId } = router.query as ...

Selector in ngrx store is returning an undefined property

I am currently facing a challenge in my project regarding the implementation of NgRx store to maintain persistent user information across components. I have encountered an issue with retrieving data from the store using selectors. Upon checking the consol ...

Is there a way to effectively refresh in Angular while using JBoss 6.4?

In my configuration of the standalone.xml file, I have set up the following rules inside subsystem tags: <rewrite name="rule-2" pattern="^((?!.*(rest)).*)\/([\w\-]+)\/([\w\-]+)$" substitution="/$1/index.html" flags="L"/> ...

Error message: "Reading properties of undefined in Angular unit test"

I'm currently working on unit testing a component where both the component and page are importing from @bloomreach/spa-sdk. export class ThinComponent implements OnInit { @Input() component!: BrComponent; componentModels: any; page: Page; ...

Enhancing Headers in Kendo UI Angular Grid

Within the footer of a grid, it is possible to include the following code in each column, with all values appearing in the same footer: <template kendoGridGroupFooterTemplate let-group="group" let-aggregates> <span class="pull-right"& ...

How can TypeScript be used to define an onClick event that can also be triggered by keyboard input?

In the React Typescript guide, it suggests typing a click event as follows: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#basic-prop-types-examples onClick(event: React.MouseEvent<HTMLButtonElement>): void; However, buttons ...

Angular: Implement a method from a designated service as a useFactory provider within a module

One of the challenges I am facing in my Angular5 application is related to a module that I am using in the following way: import *.... @NgModule({ providers: [ AuthentificationService, { provide: AuthHttp, useFactory: Authentificati ...

When the button is clicked, it does not trigger the submit function in Next.js

Currently, I am working on a nextjs project and facing an issue with a form submission. The form includes a button that should trigger the submit action upon clicking. However, in my scenario, the onclick function is not working as expected. Here is the r ...

Link JSON object array to a form by utilizing ngModel in Angular2

My current challenge involves creating a form for a "question" object, which consists of an array of strings for answers. I am struggling to bind these answers to the question model. An initial implementation might look like this: import { Component } f ...

"Troubleshooting Issue: Angular2 NGRX/Store View Failing to

I apologize for bringing up yet another concern regarding Angular 2 view updates, as I have not been able to find a solution in previous discussions. Although I mention the use of NGRX/Store, I highly doubt that it is the reason why the view is not updatin ...

Ensuring Typescript returns the accurate type depending on given parameters

i am working with a code example that looks like the following interface BaseQuestionType { label?: string } export type RadioQuestionType = BaseQuestionType & { radio: boolean } export type TextQuestionType = BaseQuestionType & { text: strin ...