angular - 从行为主体观察到的不能正常工作
问题描述
我正在开发一个 Angular 应用程序,在该应用程序中,我尝试使用具有从 firestore 获取更新的行为主题的服务。我正在尝试创建一个函数,该函数将只返回一个带有所选项目的 observable。我的问题是,当我订阅从行为主题创建的可观察对象时,可观察对象发出一个空数组,并且在数据更改时不会再次触发。
我的服务看起来像这样
export class TripService {
constructor(private db: AngularFirestore, private store: Store<fromRoot.State>) { }
private tripSource = new BehaviorSubject([])
public trips$: Observable<any> = this.tripSource.asObservable()
updateTrips() {
return this.db.collection('trips', ref => ref.where('agentId', '==', authState.uid).valueChanges({ idField: 'id' })).pipe(
tap((trips) => this.tripSource.next(trips))
)
}
getSelectedTrip() {
return this.store.select(fromRoot.getTripId).pipe( //using ngrx to get selected trip
filter((tripId: any) => !!tripId),
switchMap(tripId => this.trips$.pipe(
map((trips: Trip[]) => trips.filter(trip => trip.id === tripId)[0])
))
)
}
}
在我的 app.component 中,我调用 updateTrips 函数来获取初始数据,并且每当 Firestore 中的数据发生更改时,它都会将新的行程记录到控制台
ngOnInit() {
this.store.dispatch(fromAuthActions.loadUser());
this.tripService.updateActiveAgentTrips().subscribe(trips => console.log('trips are:', trips)); //this logs the trips!
this.clientService.getAgentClients().subscribe()
this.destinationService.updateDestinations().subscribe();
}
我的项目组件 ngOninit 看起来像这样
ngOnInit() {
this.tripService.getSelectedTrip().pipe(
tap((trip: Trip) => this.trip = trip)
.subscribe(trip => console.log(trip)) //logs: [] and doesn't emit again
}
当 firestore 中的数据发生变化时,可观察对象在 app.component 而不是在 trip.component 中发出是有原因的吗?
解决方案
推荐阅读
- html - div 的右侧太长。我该如何解决?
- python - 在 Pandas 中,如何将过滤后的 DataFrame 中的单元格映射到原始单元格中的相应单元格?
- ios - iMessage Apple 脚本 - 尝试向可以是全名或号码的目标发送消息
- loops - 如果变量之一未定义,如何不循环
- paraview - ParaView:如何修复“PNGWriter 仅支持无符号字符和无符号短输入”?
- gdb - 无法使用 GDB 插入硬件断点
- html - Jquery 更新 div 包含
- node.js - 同时连接到 Firestore 在线和模拟器?
- javascript - 使用一个对象的值作为另一个对象的键
- python - 矢量化 itertools combination_with_replacement