离线访问数据
Cloud Firestore 支持离线数据持久化。这一功能会为您的应用正在使用的 Cloud Firestore 数据缓存一份副本,以便让您的应用可以在设备离线时访问数据。您可以写入、读取、监听和查询缓存的数据。
当设备恢复在线状态时,Cloud Firestore 会将您的应用在本地所做的任何更改同步到 Cloud Firestore 后端。对于同一文档的多次更改,最后一次写入的内容会生效。
您无需更改用于访问 Cloud Firestore 数据的代码,即可使用离线持久化功能。启用离线持久化后,Cloud Firestore 客户端库会自动管理在线和离线数据访问,并在设备恢复在线状态时同步本地数据。
配置离线持久化
在初始化 Cloud Firestore 时,您可以启用或停用离线持久化:
- 对于 Android 和 Apple 平台,离线持久化默认处于启用状态。如需停用持久化,请将
PersistenceEnabled选项设置为false。 - 对于 Web 应用,离线持久化默认处于停用状态。如需启用持久化,请调用
enablePersistence方法。在不同会话之间切换时,系统不会自动清除 Cloud Firestore 的缓存。因此,如果您的 Web 应用涉及到敏感信息的处理,请务必在启用持久化之前询问用户其设备是否可信。
Web
// Memory cache is the default if no config is specified.
initializeFirestore(app);
// This is the default behavior if no persistence is specified.
initializeFirestore(app, {localCache: memoryLocalCache()});
// Defaults to single-tab persistence if no tab manager is specified.
initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})});
// Same as `initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})})`,
// but more explicit about tab management.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentSingleTabManager()})
});
// Use multi-tab IndexedDb persistence.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentMultipleTabManager()})
});
Web
firebase.firestore().enablePersistence()
.catch((err) => {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
// Subsequent queries will use persistence, if it was enabled successfully
test.firestore.js
