What is the best approach for iterating through the data that I obtain from an API?

When attempting to iterate through data fetched via an API, I encountered the following error message:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Below is my component code where the looping is attempted (main.component.html):

<app-editform [toDo$]="todo" *ngFor="let todo of cs.$todos"></app-editform>

Here is the constructor section from main.component.ts:

import {ConfigService} from '../service/config.service';

constructor(public cs : ConfigService) { 
}

And this is the contents of my config.service.ts file:

import {TodoService} from './todo.service';
import { Observable } from 'rxjs';

export class ConfigService {

    public $todos: Observable<TodoService[]>;

    constructor(private http:HttpClient) {
        this.getGlobalData();
    }

    public getGlobalData(): void {
        this.$todos = this.getToDoData();
    }

    public getToDoData(): Observable<TodoService[]> {
        return this.http.get<TodoService[]>(`${this.url}`);
    }
}

Answer №1

It appears that the error message you received is accurate. Angular can only iterate over arrays.

To resolve this issue, make sure to include the | async pipe in order to convert your observable into an array.

<app-editform [toDo$]="todo" *ngFor="let todo of cs.$todos | async"></app-editform>

Answer №2

To access the data in an Observable, you need to subscribe to it. This will allow you to retrieve the array of TodoService. Here is an example of how you can achieve this:

public todos: TodoService[];

// ..

public getGlobalData() {
    this.getToDoData().subscribe(result => this.todos = result);
}

Alternatively, you can directly convert the Observable into an array using the async pipe in your HTML template:

<app-editform [toDo$]="todo" *ngFor="let todo of (cs.todos | async)"></app-editform>

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

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Streamlining Your Workflow: Using Angular to Edit Multiple Objects Simultaneously

I utilize a table to display data retrieved from my API. In my .ts component, I use the following method to access the service data: getBloques() { this.configuracioncvService.getBloques() .subscribe(res => { let bloque ...

Having compatibility issues between Primsa 2 and NestJS when running spec tests

Recently, I've been experimenting with NestJS and integrating it with Prisma 2. One particular challenge I'm facing revolves around testing. All my failed tests seem to be related to the entity object not being recognized in the PrismaService. Ea ...

Error TS2532: The item may be undefined when using the array.map() method

Despite understanding that this TypeScript error is just a warning, I haven't been able to resolve it when it appears on the .map method. const files = require.context("./", true, /\.vue$/i); files.keys().map(key => Vue.component( ...

How can I eliminate the back button from my personalized login component in ngx-admin/Nebular?

After carefully following the steps outlined in the guide from , I successfully created a custom login component. However, I am now facing an issue - how do I remove the back button from this component? https://i.sstatic.net/WJT64.png ...

The custom validation in nestjs is throwing an error due to an undefined entity manager

I've been working on developing a custom validation for ensuring unique values in all tables, but I encountered this error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getRepository') TypeError: Cannot read proper ...

'React' was referenced prior to its declaration

I'm currently working on a project using create-react-app, TypeScript, and ESLint. I encountered the following error during the build process: Line 1:8: 'React' was used before it was defined @typescript-eslint/no-use-before-define The co ...

Creating a global user object accessible to all Angular2 components

Hey there! I've successfully shared the Parent container's property with an attribute directive and inputs, but it's not working when the child component is brought in using <router-outlet>. Any suggestions on how to share it with ever ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

Issue: State in React component remains unchangedDescription: A problem

I am currently working on implementing protected routes that are accessible only when a user is logged in. However, I am facing an issue with retrieving the loggedIn state in the ProtectedRoutes component. It always remains false, leading to a redirection ...

Is there a way to sift through an array in typescript or react native based on a specific key

I have been working with JSON data structures and I am looking to filter it in order to create separate arrays based on specific keys. Current JSON Data: data: { message: 'Customer Transaction', errorCode: null, data: [ ...

Determine whether the current time falls within the specified time slots and check if the day is included in the provided array of days

Listing my Weekly Schedule: weekly_schedule: any[] = [ { id: 0, value: 'Monday' }, { id: 1, value: 'Tuesday' }, { id: 2, value: 'Wednesday' }, { id: 3, value: ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Challenges arise when employing reduce with data types in an object

I want to transform an object in a function so that all keys are converted from Camel case to Pascal case. My Declaration: export interface INodeMailerResponseLower { accepted: string[]; rejected: string[]; envelopeTime: number; messageTim ...

Employing a boolean constant to verify if a parameter has been specified

Struggling with TypeScript version 2.8.3, I'm confused as to why the code below is failing to recognize that params is defined inside the if block. const testFunction = (params?: string) => { const paramIsDefined = typeof params !== 'undefi ...

Tips for choosing the correct type of object to use for styling in Vue/Typescript: { }

This is how I implement styling in my Vue TypeScript project. private styleTableObject: CSSStyleSheet = { width: '100%', height: '76%' } I am being forced to use the any type. private styleTableObject: any = { ...

What is the reason behind the necessity of the @Injectable decorator for HTTP service in Angular 2, while a custom service does not

What is the reason behind needing to include @Injectable when performing Dependency Injection with http, but not requiring it when implementing DI with a custom service? Illustratively: //no @Injectable() needed in this case export class Test { construct ...

What is the best way to link assets within an Angular custom element (Web Components)?

After successfully creating a web component and referencing an image from my asset folder, everything was running smoothly on my local environment. However, when I published my custom element to Firebase hosting, I encountered some issues. When trying to ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...