如何使用@angular/fire 17和ionic @ionic/angular 7.6.2配置firestore以完全脱机工作?

piwo6bdm  于 12个月前  发布在  Ionic
关注(0)|答案(1)|浏览(122)

我对使用angular ionic和firebase进行严肃的应用程序开发还比较陌生。
我现在试图弄清楚如何配置离线能力/无限缓存大小与角火,几天-我绝对迷路了!
我甚至找不到一个很好的文档,这让我想知道,如果这是可能的,虽然相当多的现有API代码在angular/fire表明,它应该是可能的。
到目前为止,我能够实现的是使用disableNetwork()和enableNetwork()函数,然后真正导致数据从该高速缓存加载。但这对我一点帮助都没有-如果在应用程序启动的时间点没有网络连接-在这种情况下,当我试图从firestore加载第一段数据时,我完全被卡住了。这也不是我需要的,因为它不会在离线状态下持久化对日期的任何更改,这是firebase的核心特性(我不确定angular/fire支持多少)。
我真的希望你们能帮助我,我感谢任何提示。
到目前为止,我初始化firebase的方式可以在下面的孔德片段中看到。
我正在开发的独立Angular 应用程序的主要.ts:请注意:没有任何代码试图配置与离线存储/无限缓存相关的任何内容,因为我完全一无所知,到目前为止我尝试的一切都不成功。

import { APP_INITIALIZER, enableProdMode, importProvidersFrom } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';
import { environment } from './environments/environment';
import { IonicStorageModule } from '@ionic/storage-angular';
import { Drivers } from '@ionic/storage';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { getAnalytics, provideAnalytics, ScreenTrackingService, UserTrackingService } from '@angular/fire/analytics';
import { getFirestore, provideFirestore, CACHE_SIZE_UNLIMITED, getPersistentCacheIndexManager, enablePersistentCacheIndexAutoCreation, PersistentLocalCache, Firestore } from '@angular/fire/firestore';
import { FirestoreDataService } from './app/firestoredata.service';
import { AuthService } from './app/services/auth.service';
import {Injectable, Inject } from '@angular/core';

if (environment.production) {
  enableProdMode();
}


bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    importProvidersFrom(
      IonicModule.forRoot({}),
      IonicStorageModule.forRoot({
        driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage],

      }),
    ),
    provideRouter(routes),
    importProvidersFrom(HttpClientModule),
    importProvidersFrom(TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    })),
    importProvidersFrom(provideFirebaseApp(() => initializeApp(environment.firebaseConfig))),
    importProvidersFrom(provideAuth(() => getAuth())),
    importProvidersFrom(provideAnalytics(() => getAnalytics())), 
    importProvidersFrom(provideFirestore(() => getFirestore())),
    ScreenTrackingService, UserTrackingService,
    {
      provide: APP_INITIALIZER,
      useFactory: () => initializeMyApp,
      multi: true,
      deps: [AuthService, FirestoreDataService, Firestore]
     }
  ],
});

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

字符串

6ljaweal

6ljaweal1#

好后相当多的撞击我的头靠在最近的墙上,我终于想出了一个不太满意的解决方案,你可以在下面找到.我离开那里的FIXME仍然会有一些东西,我会非常感激有一个解决方案。.

import { APP_INITIALIZER, enableProdMode, importProvidersFrom } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';
import { environment } from './environments/environment';
import { IonicStorageModule } from '@ionic/storage-angular';
import { Drivers } from '@ionic/storage';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { FirebaseApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { getAnalytics, provideAnalytics, ScreenTrackingService, UserTrackingService } from '@angular/fire/analytics';
import { getFirestore, provideFirestore, PersistentCacheSettings, CACHE_SIZE_UNLIMITED, getPersistentCacheIndexManager, enablePersistentCacheIndexAutoCreation, PersistentLocalCache, Firestore, persistentLocalCache, initializeFirestore, FirestoreSettings, PersistentTabManager, persistentMultipleTabManager, enableIndexedDbPersistence } from '@angular/fire/firestore';
import { FirestoreDataService } from './app/firestoredata.service';
import { AuthService } from './app/services/auth.service';
import {Injectable, Inject } from '@angular/core';

if (environment.production) {
  enableProdMode();
}

let fsapp: FirebaseApp ;
let fs: Firestore;

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    importProvidersFrom(
      IonicModule.forRoot({}),
      IonicStorageModule.forRoot({
        driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage],

      }),
    ),
    provideRouter(routes),
    importProvidersFrom(HttpClientModule),
    importProvidersFrom(TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    })),
    importProvidersFrom(provideFirebaseApp(() => 
    {
      fsapp = initializeApp(environment.firebaseConfig)
      return fsapp
    }
    )),
    {
      provide: APP_INITIALIZER,
      useFactory: () => initializeMyApp,
      multi: true,
      deps: []
    },
    importProvidersFrom(provideAuth(() => getAuth())),
    importProvidersFrom(provideAnalytics(() => getAnalytics())), 
    importProvidersFrom(provideFirestore(() => fs)),
    ScreenTrackingService, 
    UserTrackingService
  ],
});

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

function initializeMyApp(): Promise<void> {
  return new Promise<void>((resolve, reject) => {

    console.log("initializeMyApp")
    
    const plc = persistentLocalCache( {cacheSizeBytes: CACHE_SIZE_UNLIMITED, tabManager: persistentMultipleTabManager()} as PersistentCacheSettings ); //
    initializeFirestore(fsapp, { cache: plc } as FirestoreSettings);
    fs = getFirestore()

    // FIXME in future: Not sure why the above code does not get the job done of this deprecated enableIndexedDbPersistence function...
    enableIndexedDbPersistence(fs, { forceOwnership: !globalThis.localStorage }) // forceOwnership for web worker
    .then(() => console.log("Offline persistence enabled"))
    .catch(error => {
        switch (error.code) {
            case 'failed-precondition':
                console.log("Offline persistence already enabled in another tab")
                break
            case 'unimplemented':
                console.log("Offline persistence not supported by browser")
                break
            default:
                console.error(error)
        }
    })

    const im = getPersistentCacheIndexManager(fs)
    if(im!=null){
      enablePersistentCacheIndexAutoCreation(im);
    }
        
    resolve( )

  });
}

字符串

相关问题