Getter and setter methods in Angular Typescript are returning undefined values

I am facing a challenge in my Angular project where I need a property within a class to return specific fields in an object. Although I have implemented this successfully in .Net before, I am encountering an issue with getting an "Undefined" value returned.

Even though I can confirm that the properties (transLanguageId, transLangDesc, translation) are populated on the IBatchFile, they do not seem to be coming back in the GET request. Additionally, not even a console.log statement appears in the GETTER. It seems like the GETTER code is not being accessed.

What could be causing this problem?

Any help or guidance on this matter would be greatly appreciated.

model.ts

export class TranslationItem {  
  id: number;
  language: string;
  translation: string; 
}

export class IBatchFile {
  constructor(_transData: TranslationItem) {
    this._transData = new TranslationItem();
  }
  private _transData: TranslationItem;

  get transData(): TranslationItem {      
    this._transData.id = this.transLanguageId;
    this._transData.language = this.transLangDesc;
    this._transData.translation = this.translation;     
    return this._transData;
  };
  set transData(value: TranslationItem) {
     this._transData.id = value.id;
     this._transData.language = value.language;
     this._transData.translation = value.translation;
  };
  transLanguageId: number;
  transLangDesc: string;
  translation: string;
}

batchdocList.ts

private _batchFileListResults$ = new BehaviorSubject<IBatchFile[]>([]);

public loadDocList(batchid) {
  this.urlservice.getBatchFiles(batchid)         
  .subscribe(result => {      
    this._batchFileListResults$.next(result); //**result is of class IBatchFile**        

    this._batchFileListResults$.value.forEach(item => {          
      console.log(item.transData);  //**returns Undefined**
    });
}

url.service.ts

getBatchFiles(batchId: number) {             
        return this.dataservice.getBatchFiles(config.resources.Api.gatewayUri + config.resources.Api.getBatchFiles+"/"+batchId);
     }

data.service.ts

getBatchFiles(url:string): Observable<IBatchFile[]> {        
        return this.http.get<IBatchFile[]>(url)
        .pipe(map(response => response))
        .pipe(catchError(this.handleError));
    }

Answer №1

When working with HttpClient in Angular and have a Class X, it's important to note that http.get<X> does not directly return an instance of the X class.

The fields may be populated correctly, but the prototype chain is not maintained. You can verify this by checking the constructor in your browser DevTools:

result.constructor  //ƒ Object()

Compare this with creating a new instance of the X class manually:

const x = new X();
x.constructor       //class X

This means that any methods or accessors added to the prototype of the object are missing in the result object.

To avoid this issue, one approach is to use types (type X) instead of classes when defining return types for HttpClient get requests. Types are compiled away, eliminating these discrepancies.

Another option is to transform the output from HttpClient.get and instantiate real classes using constructors.

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

The method insertFusionCharts cannot be called in Angular when using jQuery

I have integrated the following scripts into my angular project <script defer src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="assets/js/jquery.min.js"></script> <script ...

Finding the file path to a module in a NextJS application has proven to be a challenge when utilizing the module

Currently, I am utilizing the webpack plugin module-federation/nextjs-mf, which enables us to work with a micro-frontend architecture. Based on the official documentation and referencing this particular example, it is possible to share components between ...

Retrieving a list of actions triggered: Redux

In my Angular project, I am utilizing Redux to manage state and handle API calls. While exploring the redux devtools, I discovered a comprehensive list of executed actions. Is there a method to access a similar list of actions triggered within my angular a ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Save solely the timing information in Mongodb

Looking for advice on storing time values in MongoDB? Users will be inputting times as strings, such as "05:20", and you need to convert and store this data correctly. Any suggestions on how to achieve this? I've attempted using the Date object with ...

Jetbrains WebStorm has issued a caution about experimental support for decorators, noting that this feature is in a state of flux and may

No matter how long I've been searching, I can't seem to get rid of this warning even after setting the experimentalDecorators in my tsconfig file. I'm currently working on an Ionic project with Angular, using webstorm by JetBrains as my IDE. ...

Guide on embedding a module into another module

I created a component called barchar. There is another module component located at src\app\modules\dashboard\page and this file contains the module. However, barchzt does not have the module. How can I utilize barchzt in the src&bsol ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Navigating through PWAs and implementing deep linking in both single page applications (SPAs) and multi-page applications

QUESTION: How can navigation, history, and deep-linking be managed in a PWA without relying on a heavy JS Framework? Tasked with transitioning an existing shopping website from Angular 1 SPA to a Multi Page App (MPA) PWA, I find myself grappling with desi ...

Enforcing strict property validation on variables passed into TypeScript functions

Is there a method to enforce excess-property checking, not only for an inline object literal but also one derived from a variable? For instance, let's say I have an interface and a function interface Animal { speciesName: string legCount: nu ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Verify the accuracy of each object in an array by comparing it to an enum and confirming its validity

I am trying to determine how many matches/true values there are based on the values of all objects in an array, compared to an enums value. My array of objects is structured like this: const jobs = [{ description, title, }... ] In addit ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Ensuring that Vue3 Typescript app focuses on input element within Bootstrap modal upon opening

I am facing a challenge with setting the focus on a specific text input element within a modal dialog. I have tried various methods but none seem to achieve the desired outcome. Here is what I have attempted: Attempt 1: Using autofocus attribute. <inpu ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

Utilizing a TypeScript Variable as a Tagname in an HTML File within Angular

This specific problem is originally documented in this post. Despite being flagged as a duplicate, my scenario differs because the HTML content at hand is too extensive for utilizing innerHTML. The structure of my component's HTML file is as follows: ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

Angular and ASP.NET: Successful Http Get Web Api request, but Angular fails to display any retrieved values

I've recently created a basic WebApi using asp.net core, here's a snippet of the code: [HttpGet("GetHomePageData")] public IActionResult GetHomePageData() { HomePageData HomePageData = new HomePageData() { ...

Troubleshooting Nested Handlebars Problem

After creating a customized handlebar that checks for equality in this manner: Handlebars.registerHelper('ifEquals', (arg1, arg2, options) => { if (arg1 == arg2) { return options?.fn(this); } return options?.inverse(t ...