【发布时间】:2018-09-11 23:53:17
【问题描述】:
return 语句在变量的 foreach 之外返回 null 值,我知道 foreach 循环创建了自己的范围,我需要返回值,我该怎么做.....
this.selectedUserMessages = this.changeUserList.switchMap(Userid => {
if (Userid) {
var self = this;
this.loadingSerivice.isLoading.next(true);
var ref = db.database.ref(`wfffsdf/usesdfdsfsrs/${Userid}/ress`);
var i = 0;
ref.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
// childData will be the actual contents of the child
var invitedList = childSnapshot.val();
self.invList.push({
invitedid: invitedList
});
var invitedlistid = self.invList[i]['invitedid']['invitedBy'];
//console.log(invitedlistid);
if (invitedlistid == "asfsafafasfsafsafs") {
//console.log("thread"+threadKey);
self.ChatKey = key;
//console.log(self.ChatKey+""+ db.database.ref(`1dfgsdfgdfhfdh/tdfsdfhsfhfhfdh/${key}/messages`));
}
i++;
});
self.chatMessages = self.getMessages(self.ChatKey);
// console.log(self.chatMessages);
});
return this.chatMessages;
}
return of(null);
}
return this.chatMessages 给出空值...
【问题讨论】:
-
在 Javascript 中,
var具有函数级范围。ForEach创建它自己的范围,因为您正在向它传递一个函数。但是,这是内部变量的范围。外部变量被捕获并在 ForEach 内部正常工作。范围不是你的问题。您的问题是您正在使用 Promise 来处理数据库查询,然后尝试立即返回流。您正在混合 Observables 和 Promise。then中的所有内容都在return this.chatMessages之后执行。给我一分钟给你找一个使用 Rx 的例子。 -
感谢您的回复@JamesPoag,我是 Angular 和 Firebase 的新手
-
好的,这是RxFire。这是来自 Firebase 团队的一个相对较新的包,用于使用 RxJS Observables。由于您使用的是实时数据库,因此您需要look at these examples。 List() 将发出子更改流。您可以通过
map()运算符pipe()此流进行额外处理(或提取val()并包含key,如示例中所示)。您在map()中所做的与您在 ForEach 中所做的类似。 -
Here is a video 演示使用 RxFire。他们使用 FireStore 而不是 Realtime 数据库,但该网站上还有其他与 Rx observables 相关的视频。
-
谢谢,会调查的
标签: javascript angular firebase firebase-realtime-database