What is preventing me from retrieving a value from a member function or method within a TypeScript class instance?

I am facing an issue with the FileInfo class that implements the IFileInfo interface. This class has an instance member function ext and a function getExt(). Within my component, there is a private method named openTempFolder() which makes an HTTP call to retrieve an Array of FileInfo. However, I keep receiving a TypeError indicating that getExt() is not a function, and calling ext returns Undefined. What could be the mistake in my implementation?

Here is the relevant code snippet,

export class FileInfo implements IFileInfo {
  constructor(
    public exists: boolean,
    public length: number,
    public physicalPath: string,
    public name: string,
    public lastModified: Date,
    public isDirectory: boolean,
    public ext: () => string,
  ) {
    this.exists = exists;
    this.length = length;
    this.physicalPath = physicalPath;
    this.name = name;
    this.lastModified = lastModified;
    this.isDirectory = isDirectory;
    this.ext = () => {
      return this.name.replace(/^.*\./, '');
    };
  }
  getExt() {
    return this.name.replace(/^.*\./, '');
  }
}

When using the class in my component, it looks like this,

export class FileManagerComponent implements OnInit, OnDestroy {
  @ViewChild('fileManager') public fileManager;
  public contents: Array<FileInfo> = new Array<FileInfo>();
  private unsubscribe: Subject<void> = new Subject();

....

 private openTempFolder() {
    this.httpService
      .getRequest<Array<FileInfo>>('FileManager/OpenTemporaryDirectory/Uploads')
      .subscribe((r: HttpResponse<Array<FileInfo>>) => {
        this.contents = r.body;
        this.contents.forEach(e => {
          console.log(e.getExt()); // TypeError
          console.log(e.ext()); // Undefined
        });
      });
  }
}

Answer №1

Even though you specify the parameterized type in the httpService.getRequest() method, HTTP calls do not return objects of the FileInfo class. Instead, they return an array of plain JavaScript objects that do not contain the getExt() method.

For solutions to this issue, refer to this question for some helpful suggestions.

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

Experiencing the error "f.ngOnChanges is not a function in target es5" while using Angular4

Encountering an issue f.ngOnChanges is throwing an error The problem arises when my tsconfig.json file is configured to target es5. However, everything works fine if I set the target to es6. Is there a way to make ngOnChange function properly with es ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

Is it necessary to unsubscribe from an Angular HTTP-Request when using switchMap?

I have a question about managing subscriptions in my Angular application. I'm currently using the combineLatest operator to create an observable from two Angular observables, route.params and route.queryParams. This combined observable is then used as ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

Sorting does not function properly when utilizing the primeng p-datatable for custom sorting

I am working on an Angular 4 application that uses PrimeNG for a datatable, and I need assistance sorting by the date field named received_at. I have created a StackBlitz with the code I've tried so far: StackBlitz link - PrimeNG datatable Here is ...

Using TypeScript to destructure arrays within a parameter list

As I delve into TypeScript, my focus is on mastering array destructuring within the arguments list. While object destructuring is feasible using this method: let foo = function({firstname, lastname}){...} foo({ firstname: 'ralph', lastname ...

Utilizing statuses in Typescript React for conditional rendering instead of manually checking each individual variable

It's common for developers, myself included, to perform conditional rendering by checking variable values like this: import React, { useState, useMemo } from 'react' const Page = () => { const [data, setData] = useState<any[]>() ...

Is there a way to determine the specific type of a property or field during runtime in TypeScript?

Is there a way to retrieve the class or class name of a property in TypeScript, specifically from a property decorator when the property does not have a set value? Let's consider an example: class Example { abc: ABC } How can I access the class or ...

Using Express and Node.js, fetch an image from one localhost and transfer it to another localhost

I am currently developing a NodeJs and Angular app The server is running on http://localhost:9000 While the app itself runs on http://localhost:4200 One of my endpoints looks like this http://localhost:9000/users, which I use to fetch all user data The ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

Why does WebStorm fail to recognize bigint type when using TSC 3.4.x?

Currently, I am working on the models section of my application and considering switching from using number to bigint for id types. However, despite knowing that this is supported from TSC 3.2.x, WebStorm is indicating an error with Unresolved type bigint. ...

Angular 2 Cordova application experiencing challenges with updating member variables that are not reflecting changes in the associated template

In my Cordova app with Angular 2, I am facing an issue where the @Component decorated AppComponent class member variable is not updating in the view template as expected. I have noticed that the first update to the member variable gets rendered in the vie ...

What is the best way to adjust the output size for ngx-webcam?

I am looking to determine the smallest possible size for an image that is captured. From my testing with ngx-webcam, I have found that I can adjust the minimum height of the output image based on the display height of the webcam. Is there a method to set ...

The unit test ends right before reaching the RxJS skipWhile method

of({loadstatus: Loaded}) .skipWhile(user => user.loadStatus !== Loaded) .take(1) .subscribe(user => do some stuff) I am puzzled by why a unit test is not triggering the skipWhile function in the code snippet above. When I set a breakpoin ...

Exploring the Angular TypeScript Method for Rendering Nested Objects in an Array

Within this array, I have a collection of objects that contain properties for model and color. My goal is to present these objects in a table format, with individual access to the color values. grp = [ {model: "CF650-3C", color: {Orange: 3, Black ...

Refreshing the webpage upon submitting with Angular2 and Firebase technology

Yesterday, I came across an Admin HTML template that I wanted to integrate with Firebase. However, when I tried to register and clicked on Sign in, the page would reload instead of carrying out the Firebase createUserWithEmailAndPass process. Here is a s ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...