我当前正在从rxjs 5迁移到6,我无法弄清楚如何从以前的Observable访问参数。我在rxjs 5中使用了以下代码:
return this.userProvider.getCurrentUser().concatMap(currentUser => {
return this.db.collection('chats').doc(room).collection<MessageModel>('messages', ref => ref.limit(25).orderBy("date", "desc")).stateChanges(["added"])
.map(docChange => docChange.map(doc => {
const message = doc.payload.doc.data() as MessageModel;
message.sender = (message.senderId === currentUser.userId) ? currentUser : receiver;
return message;
}).reverse());
});
我已将代码转换为rxjs 6(使用pipe
),如下所示:
return this.userProvider.getCurrentUser().pipe(
concatMap(currentUser => {
return this.db.collection('chats').doc(room)
.collection<MessageModel>('messages', ref => ref.limit(25).orderBy('date', 'desc')).stateChanges(['added']);
}),
map(docChange => docChange.map(doc => {
const message = doc.payload.doc.data() as MessageModel;
message.sender = (message.senderId === currentUser.userId) ? currentUser : receiver;
return message;
}).reverse())
);
但是,以这种方式,我无法访问currentUser,因为它只能在concatMap范围内访问。我如何能够重构代码以访问currentUser
?谢谢。
答案 0 :(得分:1)
您可以将当前用户与另一个pipe
和map
一起传递
return this.userProvider.getCurrentUser().pipe(
concatMap(currentUser =>
this.db.collection('chats').doc(room)
.collection<MessageModel>('messages', ref => ref.limit(25).orderBy('date', 'desc')).stateChanges(['added'])
.pipe(map(docChange)=>({currentUser,docChange}))
),
map(({currentUser,docChange}) => docChange.map(doc => {
const message = doc.payload.doc.data() as MessageModel;
message.sender = (message.senderId === currentUser.userId) ? currentUser : receiver;
return message;
}).reverse())
);
答案 1 :(得分:0)
似乎在您原来的RxJs 5.x代码中,您将逻辑.map(docChange => ....
应用于this.db.collection('chats').doc(room).collection<MessageModel>(....)
的结果,该结果很可能是一个Observable,它发出类似{ 1}}(s,
如果这一切都是正确的,那么您可以考虑以下几行中与您的RxJs代码接近的方法
MessageModel
在这里,我们将return this.userProvider.getCurrentUser().pipe(
concatMap(currentUser =>
this.db.collection('chats').doc(room).collection<MessageModel>('messages', ref => ref.limit(25).orderBy('date', 'desc')).stateChanges(['added'])
.pipe(
map(
docChange => docChange.map(doc => {
const message = doc.payload.doc.data() as MessageModel;
message.sender = (message.senderId === currentUser.userId) ? currentUser : receiver;
return message;
}).reverse()
)
)
)
);
运算符直接传递到map
查询的结果中,以便我们立即将db.collection
的范围包括在内。
我无法复制此案,因此这有点猜测,必须验证该方法。无论如何,我希望您能理解它背后的想法。