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.