The functionality of the list feature seems to be malfunctioning, as it is appearing in a strange manner when displayed in console.log

When I tried to use a list to store data and display it later, I encountered the following issues: Using ListOfName.lenth resulted in [Photo of console][1]. However, using Console.log(ListOfName) displayed [Photo of List in console][2]. [1]: https://i.sstatic.net/nJ43X.png [2]: https://i.sstatic.net/EQ0Kk.png

Home Component:

import { Component, Input, OnInit } from '@angular/core';
import {Subject} from "rxjs";
import {FirebaseService} from "../services/firebase.service";
import {JSDocTagName} from "@angular/compiler/src/output/output_ast";

@Component({
  selector: 'app-homework',
  templateUrl: './homework.component.html',
  styleUrls: ['./homework.component.css']
})
export class HomeworkComponent implements OnInit {
  constructor( public firebaseservise:FirebaseService) { }
  ListOfName:string[] =[]
    TempName = `<h1>dasdasd</h1>`
    tagName = ``
    Temp = 1

 GetData(){
 this.ListOfName = this.firebaseservise.GetDataFromTestAll(this.ListOfName)
  console.log(this.ListOfName.length)
   console.log(this.ListOfName)
}
  ngOnInit(): void {

  }

}

GetDataFromTestAll:

   GetDataFromTestAll(Tempe:string[]){
    this.ListOfName=[]
    this.FirebaseData.database.ref("Test").get().then(res =>{

      res.forEach(Groups =>{

        if (localStorage.getItem('Group') ==  Groups.key){
          this.FirebaseData.database.ref(`Test/`+Groups.key).get().then(r=>{
            r.forEach(l=>{
              this.ListOfName.push(String(l.key))
            })

          })
        }
        else {

        }

      })

    })

     return this.ListOfName
} 

Answer №1

The reason for this issue is due to the asynchronous nature of GetDataFromTestAll function. In your code, the value is not available until the promise resolves.

To address this, consider adding a console.log() statement like so:

 GetDataFromTestAll(Tempe:string[]){
    this.ListOfName=[]
    this.FirebaseData.database.ref("Test").get().then(res =>{

      res.forEach(Groups =>{

        if (localStorage.getItem('Group') ==  Groups.key){
          this.FirebaseData.database.ref(`Test/`+Groups.key).get()
          .then(r=>{
            r.forEach(l=>{
              this.ListOfName.push(String(l.key))
            })
            
            console.log(this.ListOfName) // <-- You have access to ListOfName here
            return this.ListOfName // <-- Make sure to return data at this point
          })
        } else {}
      })
    })
     
}

If you encounter issues related to inconsistent return statements from the function GetDataFromTestAll, consider treating it as an observable and subscribing to it. However, that may introduce additional complexities.

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

The concept of for loops and array indexes explained

Can someone explain why the value at index 3, value[3], is 6 instead of 5 in this code snippet? Based on my understanding, when i = 3, shouldn't adding value[i] (which is 3) to 2 (resulting from subtracting 1 from i) give us 5? int[] values = new in ...

Guide to implementing Apollo GraphQL subscriptions in NextJS on the client-side

As a newcomer to NextJS, I am facing the challenge of displaying real-time data fetched from a Hasura GraphQL backend on a page. In previous non-NextJS applications, I successfully utilized GraphQL subscriptions with the Apollo client library which levera ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

What exactly does ".default" signify in Angular, Typescript, or Javascript?

Could someone please clarify the significance of the ".default" in the code snippet below? I am interested in implementing this code in our project, but my understanding of the mentioned code fragment is uncertain. (I have modified my question to display ...

Are you wondering about the process of sending a notification from app "B" to app "A" on an Android device? Keep in mind that the Firebase project connections for these two apps are not the

Currently, I am working on two Android applications, let's call them "A" and "B", which are connected to different Firebase projects. My goal is to send notifications from app "A" to app "B" whenever there are updates in the firestore of app "A". This ...

By implementing set_userdata() in CodeIgniter, the existing session value is updated with the new value

Currently facing an issue with merging previous session values with current session values. Unfortunately, when trying to merge both values, the last session gets destroyed. Below is the code I am using to merge session arrays: $sess=$this->session-&g ...

Typescript includes empty spaces in its duplicate-checking process

I have been working on removing duplicate values from an array using the following code: for (var i = 0; i < a.length; i++) obj[a[i]] = a[i] a = new Array(); // Checking each object with keys to remove duplicates. for (var key ...

What is the best way to set up a variable in Typescript that will be assigned the value of an asynchronous request once it is completed?

As a newcomer to typescript, I encountered an issue that hadn't occurred in my previous project. It appears that declaring a variable before an API request inside a try-catch block leads to typescript errors when attempting to use this variable after ...

Tips for utilizing a particular field in a JSON object as the data origin while employing ng2-completer

As a newcomer to Angular and ng2 completer, I am working with an array of objects structured like this: var concepts = [ { id:, code:, concept:, display: } ............ ] The goal is to have the data source for auto suggest feature as the di ...

Converting a JSON array into an unordered list in PHP

Looking to transform a JSON array into a menu. Here's the JSON array in PHP: $menu = array('Home' => 'index.php', 'About me' => 'about.php', 'Contact' => 'contact.php'); While I c ...

Retrieving data using Angular 2's HTTP GET method

I am struggling to properly handle the success and failure responses from my API. When I receive a response in literal form, it gives me an error in the controller. Below is my service code: authentication(userName : string, password:string){ return ...

Inspect the JavaScript file for errors and find a solution to overcome them

Our website's select box has been updated to retrieve city options from a JavaScript array file using an ajax call request. This file is now dynamically created on a different server and then transferred to the static server where it is used to popula ...

The slice method for copying arrays seems to be malfunctioning

It's perplexing that even after utilizing distances.slice(), I end up modifying the original array when I make changes to the new copy. What could be causing this unexpected behavior? var distances = [ ['-1', '10', '-1&ap ...

Utilizing the <slot> feature in Angular 5 for increased functionality

Currently, I am working on a single page application (SPA) where Vue framework has been utilized for development purposes. Front-End: Vue Back-End: NodeJs Within my application, there are other sub-modules built in Angular 4. I am looking to replicate th ...

Ways to establish connections between numerous m-n relationship entries

Here is the schema I am working with: model School { id Int @id @default(autoincrement()) name String teachers Teacher[] students Student[] } model Teacher { id Int @id @default(autoincrement()) firstName String ...

How to extract data from JSON files using Angular 12

Having trouble with Angular and TypeScript. Need to fetch a GET API from Spring where the return variable is Page, but the JSON structure looks like this: "content": [ { "id": 1, "category": "TSHIRT&qu ...

Exploring ngAfterViewInit and ngAfterContentChecked

This question pertains to a common issue raised on StackOverflow multiple times. In essence, when you encounter a scenario such as: @Component({ selector: 'my-app', template: `<div>I'm {{message}} </div>`, }) export class A ...

Utilize ngModel within the <p> element in Angular 8

Here is some HTML code for displaying card information: <div class="col-md-4" *ngFor="let card of allCards"> <p class="card-text">Card Color: {{card.color}}</p> <button type="button" class=" ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

What is the best way to set a value to a decorated property within the constructor of a parent class

I am facing an issue with initializing a decorated property "name" in a User class within the parent class constructor (Base) using Object.assign. The value ends up being "undefined" when the decorator is present, but it works correctly when the decorator ...