Angular Firebase 实时数据库与承诺有关的问题
Angular Firebase Realtime DB issues with promises
我在使用 angular + firebase Realtime DB
时遇到一些问题
我在我的数据库服务中创建了这样一个函数:
getAllProject() {
return firebase.database().ref('project').once('value').then((snapshot) => {
if (snapshot.val()) {
const dataObj = snapshot.val();
return dataObj;
}
});
};
这是不言自明的。
然后在我的轮播组件中:
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 one is processed in second, result : correct data
});
}
ngOnInit() {
console.log("this.arrayProject 2 : ", this.arrayProject);
//this one is processed in first result : undefinned
}
我知道在呈现数据之前必须解析承诺,但在这种情况下,我在组件构造期间调用我的服务,那么为什么我的数据在 ngOnInit() 上未定义?
我需要在组件初始化之前准备好这些数据,因为这些数据将用于在我的轮播中呈现:img、文本等。
因为 getAllProject() returns 一个 Promise 和您在 .then() 中提供的回调在 ngOnInit 之后被调用。将其移动到 ngOnInit
async ngOnInit() {
this.arrayProject = await this.dbService.getAllProject();
console.log("this.arrayProject: ", this.arrayProject);
}
我在使用 angular + firebase Realtime DB
时遇到一些问题我在我的数据库服务中创建了这样一个函数:
getAllProject() {
return firebase.database().ref('project').once('value').then((snapshot) => {
if (snapshot.val()) {
const dataObj = snapshot.val();
return dataObj;
}
});
};
这是不言自明的。
然后在我的轮播组件中:
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 one is processed in second, result : correct data
});
}
ngOnInit() {
console.log("this.arrayProject 2 : ", this.arrayProject);
//this one is processed in first result : undefinned
}
我知道在呈现数据之前必须解析承诺,但在这种情况下,我在组件构造期间调用我的服务,那么为什么我的数据在 ngOnInit() 上未定义?
我需要在组件初始化之前准备好这些数据,因为这些数据将用于在我的轮播中呈现:img、文本等。
因为 getAllProject() returns 一个 Promise 和您在 .then() 中提供的回调在 ngOnInit 之后被调用。将其移动到 ngOnInit
async ngOnInit() {
this.arrayProject = await this.dbService.getAllProject();
console.log("this.arrayProject: ", this.arrayProject);
}