Search code examples
angularangularfire2angularfireangularfire2-offline

Angular 16 enableIndexedDbPersistence


I've managed to get @angular/fire working in an Angular standalone app, but I'm attempting to turn on the offline capabilities like I have in the past, and I'm now seeing that enableIndexedDbPersistence has been marked as deprecated. It suggests the following:

This function will be removed in a future major release. Instead, set FirestoreSettings.cache to an instance of IndexedDbLocalCache to turn on IndexedDb cache. Calling this function when FirestoreSettings.cache is already specified will throw an exception.

I've gone to the documentation that usually translates very well to how @angular/fire is used (https://firebase.google.com/docs/firestore/manage-data/enable-offline), but I don't see any obvious direction on what to do. The docs show the use of an options argument being passed into the call to initializeFirestore, but Angular apps don't seem to use this method externally (from the developer's perspective).

what I currently have is the following:

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideAnimations(),
    provideServiceWorker('ngsw-worker.js', {
      enabled: !isDevMode(),
      registrationStrategy: 'registerWhenStable:30000',
    }),
    importProvidersFrom(
      provideFirebaseApp(() => 
        initializeApp({
          // ... my info
        })
      ),
      provideAuth(() => getAuth()),
      provideFirestore(() => {
        const firestore = getFirestore();
        enableIndexedDbPersistence(firestore); // Marked as deprecated :(
        return firestore;
      }),
      provideStorage(() => getStorage())
    ),
  ],
};

Solution

  • I figured this out, finally, just before submitting my question. I took a closer look at how the provideFirebaseApp factory function provided the app, and it was calling initializeApp. So for the provideFirestore factory function, I figured maybe I COULD actually follow the documentation mentioned in my question if instead of using getFirestore(), I use the initializeFirestore(...) method, both of which return an instance of Firestore. Works like a charm if you do the following:

    export const appConfig: ApplicationConfig = {
      providers: [
        ...
        importProvidersFrom(
          ...
          provideFirestore(() => 
            initializeFirestore(getApp(), {
              localCache: persistentLocalCache({
                tabManager: persistentMultipleTabManager(),
              }),
            })
          ),
          ...
        ),
      ],
    };
    }