Ionic Firebase对Firebase数据的未定义值



我正在做我的第一个Ionic + Firebase项目,我不理解这个:

我从firebase搜索并获得一个对象,我可以在html上访问它的详细信息并向用户显示。

但是现在我需要保存该对象上的createdBy字段,以便我可以使用它在firebase上搜索它的创建者。

但是当我试图访问该信息时,它总是未定义的。为什么呢?关于如何解决这个问题有什么建议吗?

export class VisitDetailsPage implements OnInit {
public trips: Observable<HomeTripCardsModel>;
public trip: HomeTripCardsModel;
public buddyInfo;
public targetBuddyId: any;

constructor(private router: Router, private navCtrl: NavController,
public fireStorageService: FireStorageService,
private route: ActivatedRoute, public db: AngularFirestore) {
}
ngOnInit() {
const tripId: string = this.route.snapshot.paramMap.get('id');
this.db.collection('users').get()
.subscribe(querySnapshot => {
querySnapshot.forEach(doc => {
this.trips = this.fireStorageService.getTripDetail(tripId, doc.id);
this.trips.forEach((element: HomeTripCardsModel) => {
if (element?.id === tripId) {
this.trip = element;
this.targetBuddyId = element.createdBy;
}
});
});
});
// buddy
console.log(this.trip?.createdBy); // returns undefined
console.log('saved ', this.targetBuddyId) // returns undefined
}}

从Firebase异步加载数据。如果您设置一些断点并在调试器中运行,或者在subscribe方法中添加一个日志,您将看到console.log(this.trip?.createdBy)this.trip = element运行之前运行。此时,它还没有值

因此,需要数据库数据的所有代码都不需要在subscribe回调中:

this.db.collection('users').get()
.subscribe(querySnapshot => {
querySnapshot.forEach(doc => {
this.trips = this.fireStorageService.getTripDetail(tripId, doc.id);
this.trips.forEach((element: HomeTripCardsModel) => {
if (element?.id === tripId) {
this.trip = element;
this.targetBuddyId = element.createdBy;
}
});
// buddy
console.log(this.trip?.createdBy); // returns undefined
console.log('saved ', this.targetBuddyId) // returns undefined
});
});

最新更新