首页 > 解决方案 > 从行为主体观察到的不能正常工作

问题描述

我正在开发一个 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 中发出是有原因的吗?

标签: angularrxjs

解决方案


推荐阅读