Unable to create a loop within the constructor to assign API values

I created an export type shown below:

export type Program{
key: string; value: string;
}

An array of values is returned from the API like this:

apival = ["abc", "xyz" ...etc]

In my component's constructor, I am implementing the following:

program: Program[];

constructor(private service: Service){
getval = service.apival;
getval.forEach((a) => {
program.push({
key: a, 
value: ""
})})}

Currently, I am trying to assign the array values as keys to the program type using a forEach loop. However, I encounter the following error:

"Cannot read property 'push' of undefined" 

Note: Although I attempted to do this in the service itself and encountered the error : "Cannot Instantiate cyclic dependency"

Can anyone shed light on why this error occurs and suggest the best approach to assigning getval to programs[]. Whether it should be done in the service or component?

I prefer not to implement this logic in the OnInit() method.

Answer №1

Make sure to initialize your program: Program[]; properly by using

program: Array<Program> = new Array<Program>()
. Another option is to utilize a map function in order to create a new array.

this.program = getval.map(item=>{return {key:item, value:""}});

Answer №2

listOfPrograms: Program[] = [];

To access the listOfPrograms as a class variable, remember to prepend it with the keyword this (this.listOfPrograms).

An elegant one-liner in ES6 could be:

this.listOfPrograms = this.service.getAll.map(item => {id: item, name: ""});

The map function will loop through your array and create a new array based on the mapping logic provided.

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 path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

The input field cannot accommodate the lengthy value in the Mat Select option

When a user selects a value in my mat select, it doesn't display well in the selection box. The text wraps when the selection is opened, but once a choice is made, it gets cut off without proper spacing between the ellipses and the dropdown arrow. Th ...

Tips for troubleshooting Bootstrap Dropdown in a vertical navigation bar

Struggling to implement a vertical navigation bar with a dropdown menu on the third list item in Bootstrap 4, but facing issues as the dropdown options are not showing up. The template is specifically designed for an Angular component. I've gone thro ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

Resetting the datetime-local input to its initial value (ngModel) in template forms

In my Angular 6 template form, the user can modify the date/time in the datetime-local input after loading it with the latest data. However, I am struggling to reset the input back to the original date/time (loaded from array "one.classTimesLogOffRevised") ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Creating personalized labels with icons in Echarts

Can eCharts handle this task? I am looking to include a Label along with the current value. https://i.sstatic.net/dCEVU.png I have successfully almost replicated the image shown above. However, I need the Symbol to change based on the Label content and t ...

Creating dynamic captions in an Angular grid is an essential feature for enhancing the

Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

Encountering [Object] error in Angular's ngbTypeahead functionality

Here is the code for my input field in component.html: <input type="text" class="form-control" [(ngModel)]="searchQuery" [ngbTypeahead]="recommends" name="searchQuery" typeaheadOptionField="user ...

Local installation of typings tool

I am looking for a way to install typings 'locally' instead of 'globally.' I prefer not to install jquery typings globally because its version may change in the future, leading to changes in its typings. Although there is the option t ...

Setting Angular FormControl value to null within a service

My Angular form is reactive and collects mobile numbers along with other details. Here is the code snippet: component.html <form [formGroup]="contactDetailsForm"> <ngx-intl-tel-input [cssClass]="'ngxIntlInputBorder'&quo ...

The 'input' element does not recognize the property 'formControl', causing a binding issue in Angular Material Autocomplete with Angular 12

Recently, I upgraded my Angular app from version 11 to 12 along with all the dependencies, including Angular Material. However, after running 'ng serve', I encountered the following error: Error: src/app/components/chips/chips.component.html:19:1 ...

Utilizing Typescript to ensure property keys within a class are valid

Looking for advice to make a method more generic. Trying to pass Child class property keys as arguments to the Super.method and have Child[key] be of a Sub class. class Parent { method<T extends keyof this>(keys: T[]){ } } class Child extends P ...

​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors: Error: _models_user_model__WEBPA ...

Optimizing Angular 2+ for Search Engine Crawlers

My angular 4+ web application has a unique header for each route, with all components loading through Angular code which mainly consists of JavaScript. This setup is causing Google to be unable to crawl the links effectively, impacting SEO. If I were to ad ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Optimizing Node.js and Express routes by separating them into individual files: a

When using Express in a Node project along with Typescript, what are the best practices for express.Router? For instance, it is recommended to follow a directory structure like this: |directory_name ---server.js |--node_modules |--routes ---in ...

Leveraging Typescript in Firebase Cloud Functions to effectively work with intricate interfaces

When querying a collection on the app side, I am able to automatically cast the result as an interface using Positions constructor that takes in interface IPosition. However, attempting to do the same on the cloud functions side prevents the functions fro ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Utilize rxjs to effectively handle API data responses and efficiently manage the state of your application within Angular 10

I'm currently exploring the most efficient method for storing and updating data from an API, as well as sharing that data among sibling components. Here's my initial attempt: Storing the Observable export class MyExampleService { private data ...