为什么 AngularFire 不返回我的 Firestore 集合中的最新数据?



所以我正在尝试构建一个实时应用程序来在后台抓取数据(使用函数)并在Angular应用程序上显示它。函数按预期工作并在一天中更新我的Firestore集合。如何将最新的数据发送到我的前端才是问题所在。

我从在一个过滤集合上订阅valueChanges开始。这对于获取初始数据非常有效,但似乎没有检测到更改,并且UI从未使用新数据更新。

getRunners(raceUid: string, date: Date): Observable<Runner[]> {
return this.firestore
.collection<Runner>(Collections.Runners, (ref) =>
ref.where('raceUid', '==', raceUid)
.where('created', '>=', date)
.orderBy('created', 'asc')
.orderBy('number', 'asc'),
)
.valueChanges();
}

之后,我尝试通过以10秒的间隔订阅相同的valueChanges可观察对象来轮询更新的数据。但是UI仍然没有更新新数据,即使我的订阅回调确实在运行。

当我请求时,我知道更改在那里,因为当我刷新页面时,所有更改都会显示。初始调用获取最新数据,但之后似乎只使用本地缓存,从不检索实时数据?这可能吗?

我使用的是AngularFire 7.4.1,我没有在我的app.module中显式启用或禁用持久性。

编辑:这是我调用getRunners方法的代码。这个用于轮询:

this.updateInterval$
.pipe(
switchMap(() =>
this.runnerService.getRunners(raceUid, new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate(), 0, 0, 0)),
),
takeUntil(this.raceChange$),
)
.subscribe((runners) => {
this.runners = runners;
this.lastUpdated = new Date();
});

这是我最开始写的:

this.runnerService
.getRunners(raceUid, new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate(), 0, 0, 0))
.pipe(takeUntil(this.destroy$))
.subscribe((runners) => {
this.blockUi.stop();
this.runners = runners;
this.lastUpdated = new Date();
});

使用.pipemap方法将runner快照更改映射到require类型,如下所示:

在服务:

getRunners(raceUid: string, date: Date): Observable<Runner[]> {
return this.firestore
.collection<Runner>(Collections.Runners, (ref) =>
ref.where('raceUid', '==', raceUid)
.where('created', '>=', date)
.orderBy('created', 'asc')
.orderBy('number', 'asc'),
)
.valueChanges()
.pipe(
map((snapshots) => {
return snapshots.map((snapshot) => {
const data = snapshot.payload.doc.data();
const id = snapshot.payload.doc.id;
const updateTime = snapshot.payload.doc.updateTime;
return { id, updateTime, ...data };
});
}),
);
}

在Component中,我们将获得涉及类型安全的跑步者对象,然后在订阅时,您可以实现关于跑步者的逻辑。

this.runnerService
.getRunners(raceUid, new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate(), 0, 0, 0))
.pipe(takeUntil(this.destroy$))
.subscribe((runners) => {
this.blockUi.stop();
this.runners = runners;
this.lastUpdated = new Date();
});

最新更新