Exploring the Possibilities of Retrieving an Array within an Object in Angular 2

After retrieving this array from my database :

https://i.sstatic.net/OKrCH.png

This function is used to fetch the data :

getMembers(){
  this.db.list(`projects/${this.auth.userId}/${this.uploadService.pro.name}/teams/`).snapshotChanges().pipe(
    map(changes =>
      changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
    )
  ).subscribe((data:any) => 
    console.log(data)
   this.members = data;
    )
}

I am trying to display members using ngFor in Angular. Here's what I've attempted (first ngFor is for teams - second one is for members) :

<div *ngFor="let item of teams">
<p>{{item.name}}</p>
<p *ngFor="let member of item.members">{{member}}</p> //does not work
</div>

The error message received for let member of item.member is as follows :

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

Each team has a name:string and contains members within it.

export Interface Teams {
name: string;
}

export Interface Members {
name: string;
}

Initially, a team is uploaded - for instance "Programmers". Subsequently, members are added to that Team resulting in the following structure :

8468as6d84a6s8d4a6s8d4 {
name: Programmers;
members: {
FirstMember,
SeconndMemeber...
}
}

Answer №1

An error is occurring because the variable members is an object, which is not iterable. The *ngFor directive in Angular only supports iterables such as arrays, maps, and other similar structures.

To solve this issue, you can:

1. Use Object.keys() to obtain an array of keys from the object.

Please note that directly accessing the Object module is not possible in the template. You will need to create a custom pipe or method in the component.ts file to achieve this functionality. For example:

objectKeys(obj) {
    return Object.keys(obj);
}

<div *ngFor="let item of teams">
<p>{{item.name}}</p>
<p *ngFor="let key of objectKeys(item.members)">{{item.members[key].name}}</p>
</div>

2. Alternatively, you can utilize Object.values() to retrieve an array of values from the object.

objectValues(obj) {
   return Object.values(obj);
}
<div *ngFor="let item of teams">
    <p>{{item.name}}</p>
    <p *ngFor="let member of objectValues(item.members)">{{member.name}}</p>
</div>

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

What benefits does WebSocketSubject offer?

New to the world of web development, so please be patient with me... Current tech stack: Angular frontend, Tornado (Python-based) web server for the backend I've been successfully utilizing RxJs and WebSocket to communicate with the backend, followi ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

How can I identify and remove duplicate elements from an array of objects?

elements= [ { "id": 0, "name": "name1", "age": 12, "city": "cityA" }, { "id": 1, "name": "name2", "age": 7, "city": "cityC" }, { &qu ...

What is the best way to declare constant variables in index.html for Ionic 2?

I am currently working on developing an Android app using Ionic 2. I have declared a variable in the script tag within my index.html file. This constant value is intended to be used in both Ionic 2 pages and providers code. Below, I have included the snipp ...

What is the best way to repurpose a specific interface member type?

export interface Car { Model: string; TopSpeed: number; YearManufactured: number; } const FastestCarSpeed: Car.TopSpeed = 200; At the moment, we are encountering an issue with Car.TopSpeed: We are unable to access 'Car.TopSpeed' ...

Exploring the differences between NextJS API Routes and Firebase Cloud Functions

NextJS offers a convenient solution for creating your own API that can handle tasks such as authentication and database requests. For those who host their app on Vercel, is there any significant advantage to using Firebase Cloud Functions in addition to N ...

Error SCRIPT5009: 'query' is undefined

One of my goals is to trigger a function when the user moves the mouse out of an input field. <input #filter onmouseout="search(filter.value)"> The defined function looks like this: search(term: string): void { for(var i = 0; i < this.emp ...

How can one efficiently modify data structures stored within Firebase?

I need to update the attribute contact in my JSON Store object to phonenumber. Here are my Store objects as displayed on Firebase dashboard: I want to change all instances of contact: to phonenumber: across all my Store objects simultaneously. Currently, ...

Having trouble showing the specific date using the Angular datepipe

Working with angular 7 at the moment. Upon using the date pipe, I have encountered an issue where it displays the next date instead of the current one. Here's a snippet of the code: <div style="text-align: left;width: 80px;white-space:nowrap"> ...

What is the method for comparing a value in TypeScript that does not match a given value?

I am new to scripting languages and encountered an issue while using enums with if-else statements in TypeScript. To work around this problem, I have decided to use switch-case instead of if-else conditions. Despite trying !== and !===, they do not seem t ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

Type of Express middleware not defined

As I work on developing an authentication middleware for my express server, I encounter an issue where there are no Type errors in my IDE, but during the compilation process, I face a TypeError: Cannot read properties of undefined (reading protect) error. ...

Angular2's AngularFire2: Issue with Nested Observables not Displaying in the View

I am currently working on an experimental app using Ionic 2, Firebase, and AngularFire2 (which is still in alpha). I have been following a tutorial by Aaron Saunders as a foundation for my project: https://github.com/aaronksaunders/ionic2-angularfire-sam ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

Adding a structure to a sub-component within Angular 6 by inserting a template

Given the constraints of this scenario, the app-child component cannot be altered directly, leaving us with only the option to interact with the app-parent component. Is there a method available that allows us to inject the template into app-child, such as ...

Utilize *ngFor in Angular to showcase values from a nested map

In my Angular component, I have an array structured as follows: map: Map<string, Map<string, string>>; The specific value I want to display in the user interface is located within the second map. My approach involves iterating over the map a ...

Encountering a CORS error after deploying an Angular and Spring Boot application on Heroku

Currently facing challenges with an app due to CORS issues. It functions perfectly locally, but once deployed, an error occurs. Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from the origin &apos ...

Can you explain how to adjust the font size for table data in OfficeGen?

I am currently utilizing officeGen library to automatically create word documents. generateDocumentService.js: var generateReportFromTableData = function (tableData) { console.log('tableData: ', tableData); var docx = officegen({ type: &a ...

Is there a way for me to steer clear of using optional chaining in Typescript?

I'm currently working on storing object data known as Targetfarms in redux. I've defined a type named Farmstype for the Targetfarms. However, when I retrieve the Targetfarms using useSelector in the MainPage component and try to access targetfar ...