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

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...

Unable to utilize the namespace 'RouteComponentProps' as a specified type

When using TypeScript to define an interface that extends RouteComponentProp, I encountered some issues: VSCode error: [ts] Cannot use namespace "RouteComponentProps" as a type. Console error: Cannot use namespace 'RouteComponentProps' as a typ ...

What is the method for accessing the constructor type of an interface?

I am familiar with accessing a property type of an interface using interfaceName['propertyName'], but how can we access the constructor? For example: interface PromiseConstructor { new <T>(executor: (resolve: (value?: T | PromiseLike& ...

How to set up npm to utilize the maven directory format and deploy war files

Embarking on my very first pure front-end project, I decided to deploy it using Java/Maven. To begin, I set up a standard WAR project: │ package.json │ pom.xml │ tsconfig.json │ typings.json │ │ ├───src │ └───main ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

The configuration file tsconfig.json did not contain any input

After downloading angular2-highcharts through npm for my application, I encountered an error in the tsconfig.json file of the package while using Visual Studio Code: file: 'file:///c%3A/pdws-view-v2/node_modules/angular2-highcharts/tsconfig.json&apos ...

Looking for a sublime plugin that will enhance your angular view template?

When using Sublime Text with Angular (2/4), everything works great until I'm working in the view template file. The interpolation doesn't offer auto-completion for class properties that support the view, unlike what I've seen in VS Code. Ar ...

Angular 2: What is the reason for preventing the use of subscribe on the Subscriber object?

If I have an observable object o : let o: Observable<Object> = ... I am able to subscribe to this object, but why is it not permitted to subscribe to the Subscriber object? To illustrate with a real-life example: myServiceCall() { let o: O ...

Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller? In case my model is structured like this: public class Donation { public string DonorType { get; set; } //etc } But the f ...

The type 'typeof globalThis' does not have an index signature, therefore the element is implicitly of type 'any'. Error code: ts(7017) in TypeScript

I'm encountering an issue with my input handleChange function. Specifically, I am receiving the following error message: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when att ...

Continuously apply the template in a recursive manner in Angular 2 without reintroducing any duplicated components

Recently, I delved into the world of angular 2 and found it to be quite fascinating. However, I'm currently facing a roadblock and could really use some assistance. The scenario is as follows: I am working on creating a select box with checkboxes in ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...

What methods does VS Code use to display type errors in TypeScript given that TypeScript requires compilation?

TypeScript is a language known for being statically typed, giving it the ability to verify types during the compilation process and translate the code into JavaScript. Considering this, how is it possible for VS Code to detect type errors without the code ...

Encountering Duplicate Key Error When Implementing Angular, MongoDB, and Express

While working on my service, I encountered a situation where I needed to add a size when a user wants to add a product to the cart. Despite not having the size data included in the product information initially, as the size field in the database was empty ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Issue with displaying labels in ChartJS plugin on Ionic 3 platform

Currently, I am using Ionic 3 and have implemented a bar chart in my project. However, I am facing an issue where the data labels are not being displayed next to the bars on the chart. This is similar to the problem discussed in this question how to displa ...