【发布时间】:2022-11-28 06:33:46
【问题描述】:
我正在尝试使用此服务 getTodaysRoute() ,在这里我使用 .equalTo 找出今天的路由节点密钥,然后根据我的理解,我必须使用此 .on 函数快照,然后我终于可以从中获得密钥我使用此键将数据作为可观察对象获取。问题发生在 .on 函数中的代码最后执行并且第一次页面加载时我的 todaysroutekey 是未定义的。我怎样才能避免这样的情况?
getTodaysRoute(): Observable<Location[]> {
const date = new Date().toISOString().replace(/\T.*/, '');
const userdate = `${this.useremail}${date}`;
let todaysroutekey;
this.db.database
.ref()
.child('routes')
.orderByChild('user_date')
.equalTo(userdate)
.on('child_added', function ( snapshot) {
todaysroutekey = snapshot.key;
});
console.log(todaysroutekey);
return this.db
.list(`${this.routesUrl}/${todaysroutekey}/locations`)
.snapshotChanges()
.pipe(
map((locations) =>
locations.map(
(location) =>
({
key: location.payload.key,
...(location.payload.val() as {}),
} as unknown as Location)
)
)
);
}
这是我的组件代码
routeLocations: any[];
constructor(private firebase: FirebaseService) { }
ngOnInit(): void {
this.firebase.getTodaysRoute().subscribe((value) => {
this.routeLocations = value;
});
}
【问题讨论】:
标签: angular firebase firebase-realtime-database observable angularfire