Staying patient while the array loads data from Firebase so that methods can be called efficiently

As an Angular newbie, I am working on a project that involves accessing data from Firebase using an Angular service. My goal is to retrieve this data, store it in an array, and then perform some operations on that array. However, due to my limited experience with Angular, I'm unsure about the best way to achieve this. I understand that subscribe() is asynchronous and will require careful handling in order for my functions to work correctly.

graph.component.ts

import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import { EscortService } from '../services/escort/escort.service';
import { Escort } from '../data/escort.data';
import * as d3 from 'd3';

@Component({
  selector: 'app-graph',
  templateUrl: './graph.component.html',
  styleUrls: ['./graph.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class GraphComponent implements OnInit {

       escortList : Escort[] = [];

        constructor(private escortService : EscortService, private element: ElementRef){
        } 

        ngOnInit(){
            this.getData();
            this.generateBarChart();
        }

        getData(){
            var esc = this.escortService.getData();
            esc.snapshotChanges().subscribe(item => {
              this.escortList = [];
              item.forEach(element => {
                    var y = element.payload.toJSON();
                    y["$key"] = element.key;
                    var currentEscort = (y as Escort);
                    if(currentEscort.status == 'Completed'){
                        console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
                        this.escortList.push(currentEscort);
                     }
              });
           });
        }

Answer №1

It is recommended to make escortList an Observable.

    private const escortList = new ReplaySubject<Escort[]>();
    get escortList() : Observable<Escort[]> {
        return this.escortList.asObservable();    // By returning the observable, it prevents callers from directly calling 'next' on the subject.
    }

    constructor(private escortService : EscortService, private element: ElementRef){
    } 

    ngOnInit(){
        this.getData();
        this.generateBarChart();
    }

    getData(){
       let esc = this.escortService.getData();
       esc.snapshotChanges().subscribe(item => {
          const newEscortList = [];
          item.forEach(element => {
                let y = element.payload.toJSON();
                y["$key"] = element.key;
                let currentEscort = (y as Escort);
                if(currentEscort.status == 'Completed'){
                    console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
                    newEscortList.push(currentEscort);
                 }
          });
          this.escortList.next(newEscortList);
       });
    }

To receive updates in your component, simply subscribe to the Observable and remember to unsubscribe when necessary.

Answer №2

I encountered a similar issue and found a solution. To resolve this, you should add an *ngIf condition to the component in the app.component.html file (or any parent element) that checks if the variable is_loading is false. The value of is_loading can be toggled by your service - initializing as true, but changing to false once data retrieval is complete.
I hope this information proves helpful!

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 quick and easy guide to effortlessly removing and adding classes using Angular's Renderer2

Is there a way to efficiently add and remove a class from an element with just two lines of code, instead of using multiple if-else statements? Have you tried this method? (It's not working for me though.) constructor(private renderer: Renderer2,priv ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

``Engulfed in a sea of NgRx ViewModel

Apologies if this is unclear, there might be a fundamental aspect that I am overlooking, but here is my current issue: I am fetching a list of items from the backend, similar to: interface Item { id: number; userId: number; categoryId: number; } ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

Is it possible to append additional fields to an already existing document by knowing the value of its title field rather than its id?

When creating city documents, I typically include fields such as title and description. Is there a way to later add additional fields to a specific city by referencing the city title instead of the id? First elements added public createSavedCity(title: s ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

Comparing SomeType to SomeType[] - Which One Is Better?

Using a constant string value to narrow down a union type is simple and effective: type Payload1 = { /* ... arbitrary type ... */ }; type Payload2 = { /* ... arbitrary type ... */ }; type T1 = { type: 'type1', payload: Payload1 } type T2 = { type ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...

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) => { ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Struggling to navigate the use of Firebase v3 for hosting my React demo

I need assistance with hosting React apps on Firebase. I recently followed the instructions provided in the new v3 documentation on Firebase.com, but I am unsure about which files/assets should be placed in my public directory. The documentation seemed a b ...

What is the process for exporting a class to a module and then importing it into another module using TypeScript within an Angular environment?

I have a class called IGeneric that is exported to module A and imported into module B. However, I am unable to use this exported class in module B. Please note that the exported class is not a component, directive, or service; it is a plain TypeScript cl ...

What is the recommended substitute for the "any" type in TypeScript?

Code Slider.tsx import { useSelector, connect } from "react-redux"; import { ProductType, ProductItem, StateType } from "types"; const Slider = ({ products, number }: any) => { ------------------> what type? // const number = ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Having Trouble Displaying Data in HTML After Making a Get Request

Upon initialization, I retrieve the data using ngOnInit() ngOnInit(): void { this.http.get<any>(this.ROOT_URL + this.cookieService.get('cookie-name')).subscribe( function(res) { this.tableData = res.atVendor; co ...

Selecting elements from an array of objects using TypeScript in a React application

I'm having trouble picking only specific values (name, category, amount, price) from the items array in the Order interface and passing them as props to OrderItem. I think I need to iterate over the array but I'm not sure how to do it. I couldn&a ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Using typescript with Jest does not support directly importing default exports

I developed a React application using Typescript and here is the tsconfig file I used in my project. I have no issues with importing the defaults properly as all my files include import React from 'react'. { "compilerOptions": { & ...

Why is Firebase Deploy only detecting 1-2 files? It might be due to the default index of Firebase hosting

I'm currently in the process of deploying my Angular App to Firebase Hosting. However, I am encountering an issue where it only displays the default firebase index hosting with no changes. To set up the deployment, I have used firebase init and speci ...