angular - 比较 2 不同结构的 Observable
问题描述
我有 2 个来自带有 angularfire 的 firebase 并使用 rxjs 的 observable
private boatsCollection: AngularFirestoreCollection<Boat>;
boats: Observable<Boat[]>;
private bookingsCollection: AngularFirestoreCollection<Booking>;
bookings: Observable<Booking[]>;
结构没有行进,但bookings
收集文件ID'S
包含有关boat
(所以船id
)的信息
我想过滤船,只留下 ID与预订收集文件值不ID
匹配的这些文件。
如何使用 rxjs 实现这一点?
ngOnInit() {
// Subscribe to route params and get user's selected date
this.sub = this.route.params.subscribe(params => {
this.date = Number (params['date']);
// get bookings where selected date exits
this.bookingsCollection = this.afs.collection<Booking>('bookings', ref => ref.where('date', '==', this.date));
this.bookings = this.bookingsCollection.valueChanges({ idField: 'id' });
// Boats Collection
this.boatsCollection = this.afs.collection<Boat>('boats');
this.boats = this.boatsCollection.valueChanges({ idField: 'id' });
combineLatest(this.boats, this.bookings).subscribe(
([boats, bookings]) => {
const bookingIds = bookings.map(booking => booking.boatID);
const filteredBoats = boats.filter(boat => !(bookingIds.includes(boat.id)));
console.log(filteredBoats);
},
);
});
}
解决方案
有多种方法可以做到这一点。一种方法是使用 RxJScombineLatest
函数同时从两个可观察对象获取通知,并使用 Arrayfilter
和includes
函数过滤数组。
尝试以下
ngOnInit() {
combineLatest(this.boats, this.bookings).subscribe(
([boats, bookings]) => {
const bookingIds = bookings.map(booking => booking.id);
this.filteredBoats = boats.filter(boat => !(bookingIds.includes(boat.id)));
console.log(this.filteredBoats); // <-- correct
},
error => { }
);
console.log(this.filteredBoats); // <-- wrong - will print undefined/previous value
}
现在,combineLatest
它将为它的任何源 observables 的每次发射发射。此外,所有源 observables 都应该至少发出一次。
您可以根据需要使用 RxJSzip
或forkJoin
函数。虽然 rememberforkJoin
只会在所有源 observables 完成时才会发出。
更新:异步数据
filteredBoats
是异步分配的。这意味着console.log
在订阅之外执行时,filteredBoats
还没有任何值。console.log
应该在订阅内。
更多关于异步数据的信息在这里。
推荐阅读
- javascript - 显示用户从日期输入中选择的日期
- python - 如何避免列表python中的重复?
- python - Flask - 使用 SQLAlchemy 将 FieldList 提交到数据库?
- reactjs - react.js GitHub Firebase
- python - 如何一次从 Turecaller 获取批量电话号码的详细信息
- authentication - 有没有办法在服务器端验证用户的蜡/EOS 钱包而不进行任何区块链交易?
- typescript - 元素隐式具有“任何”类型,因为类型的表达式
- css - 如何使用额外的 CSS 更改 Wordpress 中单个图像的不透明度?
- c# - 如何在 Azure 通信服务聊天中附加文件?
- javascript - 检查日期是否从开始日期开始超过 24 小时