Struggling to show data from the console on the view screen

I have a Firestore database structured in a particular way, and at the moment I am focused on retrieving data from the userFavorites collection.

Looking at My Favorite Service

   async getfavoriteList(): Promise<firebase.firestore.QuerySnapshot> {
    const user: firebase.User = await this.authService.getUser();
    if (user) 
          {
    this.FavoriteListRef = firebase
      .firestore()
      .collection(`userFavorites`);
    return this.FavoriteListRef.where('uid', '==', user.uid).get();
              }
           } 
       }

Regarding Favorite TS

  favoriteList: any; 
  public favoriteListRef: firebase.firestore.CollectionReference;


    this.favoriteService.getfavoriteList().then(favoriteListSnapshot => {
      this.favoriteList = [];
      favoriteListSnapshot.forEach(snap => {
        this.favoriteList.push({
          id: snap.id,
          favoriteList: snap.data().favourite
        });
        console.log(snap.data().favourite)
        return false;
      });
    });
  }

Upon logging the data using -- console.log(snap.data().favourite), it appears correctly within the console logs.

However, when attempting to display this data within the view utilizing the provided HTML structure, there are some issues encountered. I have also attempted outputting the data using JSON pipe.

<ion-grid>
        <ion-row>
        <ion-col size="12" >
        <ion-card *ngFor ="let favorite of favoriteList">
            <div class="card-title">{{ favorite | json }}</div>
         <div>{{favorite?.description}}</div>
        </ion-card>
        </ion-col>
      </ion-row>
      </ion-grid>  

At this point, it seems that something is not functioning as expected. What could be causing this discrepancy?

Answer №1

You have initialized an array:

this.favoriteList = [];

Next, you are adding an item to it:

 this.favoriteList.push({
      id: snap.id,
      favoriteList: snap.data().favourite
    });

As a result, you now have a nested array structure:

 favoriteList[i].favoriteList // make sure to iterate through this

To handle this code, make the necessary changes as shown below:

    <ion-card *ngFor ="let favorite of favoriteList">   
        <ng-container *ngFor="let item of favorite?.favoriteList">
            <img [src]="item.image[0]">
            <div class="card-title">{{ item | json }}</div>
            <div>{{item?.description}}</div>
        </ng-container>
    </ion-card>

Answer №2

Due to the asynchronous nature of populating your array, the initial parsing of the array in your html may occur when it is still empty. Since Angular does not refresh its view unless a new reference is provided for the array during population, manual change detection is required once the array is full. Alternatively, you can implement the following:

private favoriteListDisplay = new BehaviourSubject<any[]>([]);

Instead of using console.log, you can use:

this.favouriteListDisplay.next(this.favoriteList)

Then adjust your html like this:

<ion-card *ngFor ="let favorite of favoriteListDisplay | async">

This approach instructs Angular to trigger another cycle of change detection for displaying your data effectively.

Answer №3

While iterating through the favoriteList using

<ion-card *ngFor ="let favorite of favoriteList">
, it seems that each object in the array consists of an id and a sub-array named favoriteList.

{
  id: snap.id,
  favoriteList: snap.data().favourite
}

Your template is attempting to reference properties that are not present within the favoriteList.

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

In Bootstrap 3, rows are aligned on the same line

My issue is that two rows are coming on the same line in Bootstrap 3. Here is the code for a chat screen with two people: Code [<div class="row single-row mt-10" style="float: left !important;> <div class="col-2" styl ...

Dealing with consecutive time period inquiries in Angular

My goal is to make 4 consecutive requests in Angular, and for some of these requests, I need to send multiple requests within this.myService.startAudit() until either the timer reaches 30 seconds or we receive a non-empty response. The issue with my curren ...

Is there a missing .fillGeometry in the Figma plugin VectorNode?

The documentation for VectorNode mentions a property called fillGeometry. Contrary to this, TypeScript indicates that "property 'fillGeometry' does not exist on type 'VectorNode'". https://i.sstatic.net/ICfdw.png I seem to be missing ...

Incorporate an interface for handling potential null values using Typescript

Currently, I am utilizing Express, Typescript, and the MongoDB Node.js driver to develop my API. However, I am encountering an issue with the findOne method as it returns a promise that resolves with either an object containing the first document matching ...

Enhance the Filtering Options in Angular Material Table by Adding and Removing Multiple Custom Terms

I have been working on designing a custom filter feature using Angular's material-ui table and material-chips. This filter allows users to search for data based on multiple keywords. Users can add keywords, and the table should display matches accordi ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Differences Between Angular 2 Reactive Forms and Template Forms

We are embarking on a new Angular 2 project and are deliberating on whether to opt for Reactive Forms or Template Forms. If you want to learn more, you can refer to this article: https://angular.io/guide/reactive-forms From what I understand, the main adv ...

Prevent a specific directory from being compiled in MSBuild using Typescript

I have a unique ASP.NET MVC / Angular2 project that utilizes MSBuild for compiling my Typescript files. Within the project, there is the complete Angular2 source code along with its NodeJS dependencies, in addition to my own Angular2 code (app.ts, etc.). ...

Is it possible to define TypeScript interfaces in a separate file and utilize them without the need for importing?

Currently, I find myself either declaring interfaces directly where I use them or importing them like import {ISomeInterface} from './somePlace'. Is there a way to centralize interface declarations in files like something.interface.ts and use the ...

What steps should I take to resolve the deprecation of node-sass usage?

Having trouble with node-sass not working? Recently received a message mentioning that node-sass is deprecated and will be removed in the next major update? Despite multiple uninstallations, you haven't seen any improvements. Wondering how to tackle t ...

Tips for integrating Vanilla JS Signature Pad into an Angular 8 project

As a newcomer to Angular, I am currently facing challenges in integrating szimek/signature_pad into my application. While I have successfully incorporated other JavaScript libraries into Angular 2+ apps using the articles I've consulted, signature_pad ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

Tips for testing Observable.fromEvent

Can you provide a method to test Observable.fromEvent using jasmine? @ViewChild('d') private inputDatePicker: NgbInputDatepicker; this.subscription = Observable.fromEvent(document, 'click').subscribe((event: KeyboardEvent) => { ...

Navigating conflicts between packages that utilize TypeScript can be tricky. Here are some strategies for handling these situations

I recently encountered an issue while following a tutorial to create a WhatsApp clone using Meteor. The tutorial link is here The problem arose at the end of section 8 when I executed the $meteor reset command as directed. However, upon running the $ n ...

Guide to Reverting the Two-Way ngModel Binding Data in Angular 2

I am utilizing a form in angular 2 that includes two-way binding data value ([(ngModel)]) to enable both edit and add functionality. When a user selects the edit option on the listing page and modifies the input, the new values automatically appear on the ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

TypeScript overloading error: Anticipated 0 parameters, received 2 instead

I am facing an issue with a class containing an overloaded method that has two versions. One version does not take any arguments, while the second one can take two arguments. class DFD { ... getEndDatetime(): string; getEndDatetime(startTime?: ...

Pause for a few moments until assigning a new value to the observable

In my application, I have implemented a message service that emits messages whenever the API method is triggered. The main purpose behind this is to allow all other components in the app to utilize the service for displaying error or success messages. imp ...