Challenges with promises in Angular Firebase Realtime DB

Having some difficulties with Angular and Firebase Realtime DB.

In my database service, I created a function like this:


getAllProject() {
  return firebase.database().ref('project').once('value').then((snapshot) => {
    if (snapshot.val()) {
      const dataObj = snapshot.val();
      return dataObj;
    }
  });
};

This function is quite straightforward.

Next, in my carousel component:


import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { DbService } from '../services/db.service';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.scss']
})
export class CarouselComponent implements OnInit {

  arrayProject;

  constructor(private dbService: DbService) { 

    this.dbService.getAllProject().then((data)=>{
      this.arrayProject = data;
      console.log("this.arrayProject",this.arrayProject);
      //this log shows correct data as it is processed second
    });

   }

  ngOnInit() {

    console.log("this.arrayProject 2 : ", this.arrayProject);
    //this log shows undefined as it is processed first

  }

I am aware that a promise should be resolved before rendering data. However, since I call my service during component construction, why is my data undefined in ngOnInit()?

The data needs to be ready before the component initializes because it will be used to render images, text, etc., in my carousel.

Answer №1

It is important to note that the getAllProject() function returns a Promise, which means the callback specified in .then() will be executed after the ngOnInit lifecycle hook. To address this issue, simply place it inside the ngOnInit method.

async ngOnInit() {
    this.projectList = await this.databaseService.getAllProjects();
    console.log("Retrieved project list: ", this.projectList);
}

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

Is it possible to modify the CSS styling in React using the following demonstration?

I am attempting to create an interactive feature where a ball moves to the location where the mouse is clicked. Although the X and Y coordinates are being logged successfully, the ball itself is not moving. Can anyone help me identify what I might be overl ...

Next.js Troubleshooting: Unexpected Issue with 'use client' Triggering Error in React Client Component

Keeping it simple, here is a useState function that I am using: 'use client' import {useState} from 'react'; const Home = () => { const [fruit, setFruit] = useState('apple'); return ( & ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...

Modify the selection in one dropdown menu based on the selection in another dropdown menu using Angular 8

When I have two dropdowns, I aim to update the second dropdown with a matching JSON object based on the value selected in the first dropdown. JSON this.dropdownValues = { "mysql 8": { "flavor": [ "medium", ...

Prevent Angular from performing change detection on specific @Input properties

Within my Angular component, there are extensive calculations that take place when changes are detected. @Component ( selector: 'my-table', ... 400+ lines of angular template ... ) class MyTable implements OnDestroy, AfterContentInit, On ...

What is the best way to incorporate Electron browser windows within Angular-CLI components?

How can I use electron browser window inside components in angular-cli if it doesn't accept it? I encountered an error with fs.existsync. Are there any alternative options to integrate electron with angular2 components? var electron = require(&apos ...

React - All subsequent variable declarations must be of the same type

Running webpack in my React application results in the following error message appearing 58 times across different variables: https://i.sstatic.net/uedR7.png Removing the @types directory did not resolve the issue and instead produced a new error message: ...

Is there documentation available for the gcloud output formats, such as the JSON output for each command?

As I work to script the gcloud tool in a TypeScript-aware JavaScript environment known as SLIME, I am utilizing the --format json feature for formatting. The integration is smooth, but I find myself manual analyzing the JSON output of each command to und ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

mat-slider: experiencing delay in updating while dragging it

Incorporating @angular/material in my Angular 5 application has been quite the journey. The specific version of Angular Material that I have implemented is 5.0.2, along with @angular/animations 5.1.2. My usage of the slider component is rather straightfor ...

The ngModel in AngularJS 2 fails to update when the Jquery Date Picker date is changed

Having an issue with the Jquery UI datepicker within an angularjs 2 component. The datepicker is displaying the changed date, but it's not updating the underlying ngModel: dateSelected. dateSelected: string = ''; The date picker input fie ...

Discover the steps to obtain the css class md-inputfield within primeng by referencing the code: <span class="md-inputfield ">

Sorry for the inconvenience, but I am having trouble locating the md-inputfield class in primeng. It is crucial for me to have access to that class attributes in order to properly debug the text field. Is there any chance of resolving this issue and maki ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

Is the array index a string or a number?

Why is it that when looping over the indexes of an array they appear as strings, even though using a string to index an array is not allowed? Isn't this inconsistency puzzling? for (const i in ["a", "b", "c"]) { console.log(typeof i + " " + i + " " ...

Scoped variable in Typescript producing a generated Javascript file

I'm currently learning TypeScript through an online course, and I've encountered a problem that seems to be related to a VSCode setting. Whenever I compile app.ts, it generates the app.js file, but I immediately encounter a TypeScript error. It& ...

Using Angular, create mat-checkbox components that are dynamically generated and bound using

In my Offer class, I have a property called "units" which is an array of objects. export class Offer { public propertyA: string; public propertyB: string; public units: Unit[]; } export class Unit { public code: string, public name: ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

Streamlined method for creating forms and charts within SharePoint

When it comes to creating charts and forms on SharePoint, what is the best approach for maximizing efficiency? Using AngularJS web parts with CRUD operations. Modifying standard forms and integrating charts using JavaScript libraries and CSS. Are there ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...