Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, upon executing the code, I encounter the following error:

error

Despite this, when I examine the observable through logging, it displays like so:

observable

profile.page.ts:

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

import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';

import { UserService } from '../user.service'

import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore'

import { Observable } from 'rxjs';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})

export class ProfilePage implements OnInit {





  constructor(public afAuth: AngularFireAuth, public router: Router, public user: UserService, public db: AngularFirestore) { 


  }



  ngOnInit() {



  }

  logout() { this.afAuth.auth.signOut(); this.router.navigate(['/login']);}


}

profile.page.html:

 <ion-content>
  <ion-grid>
      <ion-row justify-content-center align-items-center style="height: 50%">
    <ion-button color="danger" size="small" shape="round" (click)="logout()">Logout</ion-button>
    <p *ngFor="let users of (username | async)">{{ users.username }}</p>
    </ion-row>
    </ion-grid>
</ion-content>  

Appreciate any assistance provided in advance.

Answer №1

The reason for the error is that your username data is not currently stored as an array. To fix this issue, you should modify your code by converting your username into an array and then pushing it into a new array.

let usernames: string[] = [];

usernames.push(users.valueChanges());

Answer №2

Hey, do you have confirmation that the variable users is actually an array?

You might want to try using console.log(users) to get a clearer understanding of the data type being passed.

Answer №3

To incorporate the mapped results from your service into an array, consider using push or unshift with a for loop and then return the modified array. Here's an example implementation:

private usersCollection: AngularFirestoreCollection<User>
    this.usersCollection = this.afs.collection<User>('user', ref => ref.orderBy('name','desc').limit(5));
        return this.usersCollection.valueChanges().pipe(map( (users: User[]) =>{
                  let modifiedUsers = [];
                  for (const user of users) {
                    modifiedUsers.unshift(user);
                  }
                     return modifiedUsers          
                }))

afs is of type AngularFirestore

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

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

The NW JS window loaded event fails to trigger when loading a URL, but functions properly when loading from a local

Having trouble triggering the loaded event on a live webpage compared to a local page. The loaded event fails to fire with this code: var mywin = nw.Window.open('http://www.google.com', {"frame": false}, function(testWin) { testWin.on(&apos ...

Is it possible to maintain the data types of each individual piece of data when it's divided into an array in

Can the data type of each field be preserved in Javascript after splitting it using the split method? Input: var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'"; When using the split method, the data type of e ...

AngularJs FileList Drag and Drop Feature

Being brand new to front-end development, I decided it would be a fun challenge to implement drag and drop functionality on an existing upload page. However, as I began integrating ng-flow (a directive that helps with drag and drop), I encountered difficul ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Most effective method for sending an HTTP Post request with a JSON body in Angular 9

Hi there, I'm currently working on a project that requires saving information from 3 text box fields. I've been struggling to figure out how to make a POST request with a JSON body. Here's what I have so far: I've been piecing together ...

Tips on how to combine or flatten arrays using rxJS

I am looking to consolidate a structured array into one uniform array. The original array structure is as follows: [ { "countryCode": "CA", "countryName": "Canada", "states": [ { "stateCode": "CAAB", "stateName": "Alber ...

Is there a way to decrease the speed of a range slider?

Recently, I created a range slider using HTML, CSS, and JS to complement my Lua Nui. It's been working smoothly for the most part, but I've noticed an issue when sliding too quickly on the slider. As I slide it to the left, certain values fluctua ...

What is the best way to start tiny-slider automatically once the video has ended?

I am currently using the tns-slider plugin and have a setup with 3 slides (2 photos and 1 video). <div class='tiny-slider'> <div class='slide slide1'> <div class='video-slide'> <video id=&qu ...

The integration of AngularFireFunctions with Ionic 5 Angular breaks down when attempting to create a production build using the --prod flag

Attempting to invoke a Firebase function using Angular Fire within an Ionic project. const callable = this.afFunctions.httpsCallable('getWeather'); const result = await callable(request).toPromise(); The functionality operates as expected in ...

Combining an Angular application within a Spring application and encountering a TypeError on a JSP page

I am currently working on integrating an Angular app into an existing Spring application. I have included the code for integration below. While it functions correctly on some JSP pages, it fails on others. Please see the description and rendered element in ...

Refreshing the View in Ionic and AngularJS Using Controller UpdatesIn this tutorial, we will

As a newcomer to both Ionic and Angularjs, I am currently in the process of developing a simple Ionic app. The main functionality involves displaying a list of classes (sessions), allowing users to book or cancel a class by clicking on an icon, and updatin ...

How can I use a button created with jQuery's .html() method to conceal a <div>?

I am facing an issue with implementing a simple banner that should appear in an empty element only when specific values are returned by an Ajax call. In the banner, I want to include a Bootstrap button that hides the entire div when clicked. Due to my la ...

Guide to building an Angular circular progress indicator using Scalable Vector Graphics (SVG)

I have designed an angular circular progress bar, but I am facing an issue with making the percentage value dynamic. I have managed to retrieve the dynamic value from an API, but I am unsure of how to implement it in creating a circular progress bar using ...

Establishing a secondary Node.js service for local communication with Parse Server

My current project involves using Node.js + Parse Server for an application. I have been utilizing the Parse SDK from the client side, but there are still many changes and refactors that need to be made. One issue I am facing is that certain logic should b ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

Unable to locate the variable named StyleSheet

I've been delving into React Native using this informative site https://www.tutorialspoint.com/react_native/react_native_animations.htm However, I encountered a setback when attempting to launch the app on my iPhone. An error message indicates that a ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

Is now the ideal moment to implement Angular 4?

When considering using Angular 4 for an enterprise SAP system, is it better to stick with Angular 2 and wait for the final release of Angular 4? There have been rapid releases of Angular 4 that may affect our decision. (View changelog) Your suggestions ar ...