"Navigating through Angular's nested components with forEach and subscribe

I am working on constructing an array based on data received from a subscription.

Currently, my code looks like this:

const dataFormat = new IData();
this.api.getData()
.pipe(
map(response => response),
tap(data => console.log('data array', data)))
.subscribe(dataResult => {
    dataResult.forEach(function (item) {
         dataFormat.title = item['title'];
         dataFormat.author = item['author'];
         dataFormat.date = item['date'];
         this.listData.push(dataFormat);
    });

});

When I try to push data into this.listData, I encounter the following error:

Potentially invalid reference access to a class field via 'this.' of a nested function

To solve this issue, I tried using let self = this with self.listData.push(dataFormat);. However, this approach only stores the last item from the loop in my array.

Answer №1

It seems like there is a scope error, which can commonly occur when using the forEach method.

Consider using a standard for loop instead of the forEach loop.

.subscribe(dataResult => {
   for(let item of dataResult) {
       dataFormat.title = item['title'];
       dataFormat.author = item['author'];
       dataFormat.date = item['date'];
       this.listData.push(dataFormat);
   }
});

If you prefer to continue using the forEach loop, pass an arrow function like this:

.subscribe(dataResult => {
   dataResult.forEach(item => {
       dataFormat.title = item['title'];
       dataFormat.author = item['author'];
       dataFormat.date = item['date'];
       this.listData.push(dataFormat);
   });
});

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

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

The material picker consistently shows the first day of the month from the assigned date

I'm currently using a material datepicker and attempting to assign a value to it from the server. The response I receive is: 21-07-2022 Since the datepicker requires a date or moment type, I am converting the response accordingly this.form.controls[ ...

Troubleshooting: Inoperative Button in Angular Material Table

My Angular Material Table has the following setup: <table mat-table [dataSource]="getItems()"> <ng-container matColumnDef="delete"> <th mat-header-cell *matHeaderCellDef></th> <td mat-cell *matCellDef=" ...

What is the best way to search through an array in TypeORM?

I am working on implementing user permissions management using TypeORM with PostgreSQL. The permissions are defined within the user entity in the following column: @Column({ type: 'text', array: true }) permissions: UserPermission[] = []; Th ...

Explaining the concept of SwitchMap in RxJS

Currently, I am utilizing Restangular within my Angular 5 project. Within the addErrorInterceptor section, there is a code snippet that invokes the refreshAccesstoken method and then retrieves the new access token in the switchMap segment. My approach invo ...

Convert JSON data to an array using Observable

My current task involves parsing JSON Data from an API and organizing it into separate arrays. The data is structured as follows: [ {"MONTH":9,"YEAR":2015,"SUMAMT":0}, {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5}, {"MONTH":11,"YEAR":2015,"SUMAMT":5392 ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

Generics in Typescript interfaces

I'm trying to grasp the meaning of T = {} within this TypeScript interface. I've searched for documentation on this usage but haven't found anything specific. How does it differ from simply using T? interface CustomProps<T = {}> { ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

After compilation, any variables declared within a module remain undefined

I have declared the following files app.types.ts /// <reference path="../../typings/tsd.d.ts"/> module App{ export var Module = "website"; //---------------Controller Base Types--------------- export interface IScope extends ng.ISco ...

Angular 2 and beyond: Managing an array of objects with nested subscriptions using the forEach method

My scenario involves working with two separate Observables. The first one is used to retrieve a list of items, which comes back as an array of objects with a key called "fakturaId": getInvoiceForResidence() { return this.httpClient.get<Invoices> ...

Is it possible for me to transfer a change to the worldwide namespace from my library?

I am looking to enhance an existing TypeScript type within the global namespace in my library and then expose it for use in other projects. Can this be done? Below is my current code: Promise.ts Promise.prototype.catchExtension = function<T>(this ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

Implementing Angular WebSocket to showcase elements in a sequential manner during chat

Currently, I am developing a chat application using Angular and socket.io. The server can send multiple events in rapid succession, and the front end needs to handle each event sequentially. // Defining my socket service message: Subject<any> = new S ...

Challenges associated with the '--isolatedModules' flag and RouterContext

After attempting to run my deno application, I encountered the following error message and I'm unsure about the cause. Has anyone else faced this issue before? Command used to run: deno run --allow-all server.ts Error: Error: TS1205 [ERROR]: Re-expo ...

Issues with the aligning of buttons using the justify-content property

The issue I'm facing involves a parent container with 3 buttons nested inside. The parent container is set to display:inline-flex, however, the justify-content: space-between property is not behaving as expected. Each button has a defined max-width in ...

Looking to update properties for elements within the Angular Material 16 mat-menu across the board?

Currently working with Angular Material 16 and I have a question regarding the height of buttons inside the mat-menu element. Here is an example of the code: <button mat-icon-button> <mat-icon>more_vert</mat-icon> </button> ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Is there a way to utilize const assertions to retrieve the explicit types from objects nested at various levels?

In reference to this question, the previous structure had a depth of 2: const grandkids = { Karen: { Ava: ['Alice', 'Amelia'], Emma: ['Sarah'], }, Mary: { Sophia: ['Grace'], }, } as const; To ext ...