Issue with retrieving an array of objects in an Angular function

Good day, I am facing an issue when attempting to retrieve an array of objects from an external function.

I have defined a class called Object with 2 properties, a constructor, and a method that returns an array containing more than 50 objects. For this example, I have simplified it to just 4 objects.

export class Object {
  formcontrolName: String;
  formcontrolTraducido: String;

  constructor(formcontrolName: String, formcontrolTraducido: String) {
    this.formcontrolName = formcontrolName;
    this.formcontrolTraducido = formcontrolTraducido;
  }

  getData() {
    return [
      { formcontrolName: 'callId', formcontrolTraducido: 'CId' },
      { formcontrolName: 'collegeCareerId', formcontrolTraducido: 'Carrera' },
      {
        formcontrolName: 'collegeDepartmentId',
        formcontrolTraducido: 'Nombre del Departamento/Centro',
      },
      {
        formcontrolName: 'detailedAreaKnowledgeId',
        formcontrolTraducido: 'Campo Detallado',
      },
    ];
  }
}

The problem arises when I try to invoke the getData function of the Object class from another component, resulting in the following error:

Type '() => { formcontrolName: string; formcontrolTraducido: string; }[]' is missing the following properties from type 'Object[]': pop, push, concat, join

import { Component, OnInit } from '@angular/core';
import { Object } from './object';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
 data: Object;
  arrayData: Object[];
  constructor() {}

  ngOnInit() {
    this.arrayData = this.data.getData;
    console.log('arrayData: ' + this.arrayData);
  }

}

view example code on stackblitz

I am new to angular and working with arrays, seeking guidance on how to resolve this issue. Thank you for your help.

Answer №1

Initially, it's important to note that the type for the property arrayData is not of type Object, which is the class being used. A more suitable type would be the same as the one returned by the method getData.

You can fetch its return type using the typescript helper type ReturnType. Therefore, a proper way to type this would be:

  arrayData: ReturnType<Object['getData']>;

I suggest avoiding naming a class as Object, as it shares the same name with JavaScript built-in Object.

The issue lies in this part of your code:

  ngOnInit() {
    this.arrayData = this.data.getData();
    console.log('arrayData: ' + this.arrayData);
  }

The error occurs because you are assigning a method to a variable that expects an array of something. You will encounter the error:

Type '() => { formcontrolName: string; formcontrolTraducido: string; }[]' is missing the following properties from type 'Object[]': pop, push, concat, join

Solution is simple, you just need to call the method like this:

    this.arrayData = this.data.getData();

Considering all this, the final code should resemble:

import { Component, OnInit } from '@angular/core';
import { Object } from './object';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';
  data: Object;
  arrayData: ReturnType<Object['getData']>;
  constructor() {}

  ngOnInit() {
    this.arrayData = this.data.getData();
    console.log('arrayData: ' + this.arrayData);
  }
}

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

Maximizing efficiency in processing multiple requests simultaneously using ajaxSetup's data

I need to enhance an existing ajax request within our CMS by adding additional data. Specifically, I am working with a media library that loads image data (json), and I want to incorporate more images from an external source. var promise_waiting = []; jQu ...

Dynamic Content in jQuery UI Tooltip

Is it possible to dynamically change the tooltip content as I drag the div that contains the tooltip? I want to display the ui.position.top in the tooltip during the drag event. I have checked the jQuery UI API documentation for tooltip content, which ment ...

The menu does not appear when I attempt to right-click on the grid header

Is there a way to add a right-click menu to the grid header? The right-click functionality works on Google links, but not on the grid header. Any suggestions on how to resolve this issue? Below is the code I'm using: http://jsfiddle.net/c7gbh1e9/ $( ...

Transforming values in a 2-dimensional array from strings to numerical data

Data From External Source Hello there, I've been utilizing the read_csv function in Python to pull data from a specified URL. The dataset I'm working with contains a column filled with character/string values, while the remaining columns are co ...

How to avoid the need to wrap all setState calls with #act in React 18?

One issue I encountered was when upgrading from React 17 to 18, ReactDom render became asynchronous. To handle this, I needed to use #act to wrap the ReactDom render. However, React also required that all setState calls be wrapped with #act. If not done, ...

A guide on merging decorated parameters to form a unified object in TypeScript

I'm currently working on a NestJS controller with multiple methods that have a similar structure, like the example below: @Post(':id/something') async doSomething( @Param('id', ParseUUIDPipe) id: string, @Body() body: Somet ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Struggling to apply filtering on an array containing multiple objects within Ionic 2

I have successfully implemented filtering on the following array: this.items = [ 'Amsterdam', 'Bogota', 'India' ]; The code used in my list.ts file is as follows: if (val && val.trim() != '') { thi ...

Embrace a variety of HTML template options when setting up a ReactJS component

Can someone help me understand how to render a component with template HTML data in ReactJS? class Options extends React.Component { render() { const othList = []; [1, 2, 3, 4, 5].forEach((t) => { othList.push(t); ...

What is the best way to arrange an array of objects in a descending order in Angular?

private sumArray : any = []; private sortedArray : any = []; private arr1 =['3','2','1']; private arr2 = ['5','7','9','8']; constructor(){} ngOnInit(){ this.sumArray = ...

What is the best way to incorporate a progress bar animation into my notification?

Seeking assistance to implement an animated progress bar that changes colors gradually over time based on a variable [timer]. Can anyone lend a hand with this? Thank you! https://i.sstatic.net/lhgeF.png $(document).ready(function(){ window.addEvent ...

Using Google App Engine with Stripe - Enable users to easily upload images for account identity verification directly through their browser using Javascript

After extensive research, I have been exploring how to enable direct browser uploads, particularly in the context of utilizing Stripe with Google App Engine, as discussed on this forum. The Stripe documentation also mentions the possibility of browser uplo ...

Conceal virtual keyboard on mobile when in autocomplete box focus

I would like the keyboard to remain hidden when the autocomplete box is focused or clicked, and only appear when I start typing. The code below currently hides the keyboard when any alphabets or numbers are pressed. However, I want the keyboard to be hidd ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

Is there a way to effortlessly zoom in on a Google map with just one mouse click?

Can the Google Maps be zoomed to a specific level with just one click of the mouse? ...

Angular child routes experiencing encryption

Struggling to find a working example of child component routing being used AFTER a parameter: Currently, profile/userName works but the children do not. { path: 'profile/:userName', component: ProfileComponent, children: [ { path: ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

The stream.write function cannot be executed as a callable expression

Struggling to create a function that accepts either a writable stream (createWriteStream) or process.stdout/.stderr in TypeScript, but encountering an error. import { createWriteStream, WriteStream } from 'fs' const writehello = (stream: NodeJS. ...

Incorporating an NPM JavaScript library into Laravel version 8

I've integrated the mobiscroll javascript component library into my new Laravel 8 app by adding the minified css/js files to the public/css and public/js directories. However, I'd like to find a more seamless way to include these components by us ...