当启用 enablePersistance 时,AngularFire returns 来自缓存和服务器
AngularFire returns results from cache AND server when enablePersistance is enabled
我在我的 Angular (11.1.1) 项目中使用 AngularFire
(6.1.4) 离线持久化,我惊讶地发现在加载时,数据提供了两次:一次来自缓存,一次来自服务器(我使用变量 fromCache
来证明来源)。
app.module.ts
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
@NgModule({
imports: [
AngularFireModule.initializeApp(Config),
AngularFirestoreModule.enablePersistence(),
AngularFireAuthModule
]
})
export class AppModule { ...}
数据库服务
this.firestoreRef.collection(collectionName, query)
.snapshotChanges()
.pipe(
map(actions => actions.map(a => {
console.log('fromCache -> ', a.payload.doc.metadata.fromCache);
}))
).subscribe(/* Just for TEST purposes */);
我认为 get()
选项的逻辑相同:
Setting to default (or not setting at all), causes Firestore to try to retrieve an up-to-date (server-retrieved) snapshot, but fall back to returning cached data if the server can't be reached.
为什么用户在线也返回缓存数据?
当然我可以监听 offline/online 事件(虽然它们不可靠)甚至是一个软件来检查客户端是否在线,并相应地使用或跳过缓存的结果,但不应该Firestore 检测到 online/offline 状态?
来自 listening to realtime updates 上的文档:
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document.
虽然这里讨论的是单个文档,但同样适用于收听多个文档。
所以您所看到的正是 Firestore 的工作原理:当您为快照附加侦听器时,它会立即触发数据的本地状态(如果有)。然后它检查服务器,这可能需要一些时间,如果服务器的状态与本地缓存不同(或者您也请求调用元数据更改),则再次使用服务器的状态触发。
我在我的 Angular (11.1.1) 项目中使用 AngularFire
(6.1.4) 离线持久化,我惊讶地发现在加载时,数据提供了两次:一次来自缓存,一次来自服务器(我使用变量 fromCache
来证明来源)。
app.module.ts
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
@NgModule({
imports: [
AngularFireModule.initializeApp(Config),
AngularFirestoreModule.enablePersistence(),
AngularFireAuthModule
]
})
export class AppModule { ...}
数据库服务
this.firestoreRef.collection(collectionName, query)
.snapshotChanges()
.pipe(
map(actions => actions.map(a => {
console.log('fromCache -> ', a.payload.doc.metadata.fromCache);
}))
).subscribe(/* Just for TEST purposes */);
我认为 get()
选项的逻辑相同:
Setting to default (or not setting at all), causes Firestore to try to retrieve an up-to-date (server-retrieved) snapshot, but fall back to returning cached data if the server can't be reached.
为什么用户在线也返回缓存数据?
当然我可以监听 offline/online 事件(虽然它们不可靠)甚至是一个软件来检查客户端是否在线,并相应地使用或跳过缓存的结果,但不应该Firestore 检测到 online/offline 状态?
来自 listening to realtime updates 上的文档:
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document.
虽然这里讨论的是单个文档,但同样适用于收听多个文档。
所以您所看到的正是 Firestore 的工作原理:当您为快照附加侦听器时,它会立即触发数据的本地状态(如果有)。然后它检查服务器,这可能需要一些时间,如果服务器的状态与本地缓存不同(或者您也请求调用元数据更改),则再次使用服务器的状态触发。