簡體   English   中英

將 Firebase 模擬器與 AngularFire 一起使用

[英]Using Firebase emulator with AngularFire

我正在嘗試在我的 Angular7 應用程序中使用新推出的Firestore 模擬器

根據此文檔,我在127.0.0.1:8080上運行開發服務器:

firebase serve --only firestore

那么,在ng serve之后,如何讓我的 AngularFire 模塊使用數據庫模擬器

我在environment.ts中嘗試了以下內容:

export const environment = {
  production: false,
  name: 'local',
  firebase: {
    databaseURL: "http://127.0.0.1:8080"
  }
};

但它不起作用,因為它需要一個“projectId”。 我嘗試將其設置為我的預生產 Firestore 數據庫,但隨后未使用開發服務器。

有沒有想過?

這是我的app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from '@app/app-routing.module';
import { AppComponent } from '@app/app.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireStorageModule } from '@angular/fire/storage';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { environment } from '@env/environment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase, 'my-super-cool-app'),
    AngularFirestoreModule,
    AngularFireAuthModule,
    AngularFireStorageModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我通過在主應用程序模塊中添加一個提供程序來實現它,該提供程序覆蓋了環境文件設置的一些變量。

請參閱 angularfire 存儲庫中對問題的此答案 示例(來自答案):

{
  provide: FirestoreSettingsToken,
  useValue: environment.production ? undefined : {
    host: 'localhost:8081',
    ssl: false
  }
}

由於我有幾個不同的環境,我讓條件查找環境中的“模擬器”屬性,如果它是 false 或未定義則返回 undefined,而不是查找生產屬性並在存在時返回 undefined:

{
  provide: FirestoreSettingsToken, useValue: environment.emulator ? {
      host: 'localhost:8081',
      ssl: false
  } : undefined
}

AngularFire v6.xx 開始更新:

FirestoreSettingsToken已更改為@angular/fire/firestore模塊中的SETTINGS

使用“Firebase 模擬器”並不像最初看起來那么明顯,因為“模擬器”實際上是模擬器的集合 設置一個並不意味着設置所有。 您甚至可以根據需要將一些設置為在本地運行,而另一些在遠程運行。

要將所有模擬器設置為在本地運行,您可以使用這些提供程序

import { AngularFireAuthModule, USE_EMULATOR as AUTH_EMULATOR } from '@angular/fire/auth';
import { USE_EMULATOR as FIRESTORE_EMULATOR } from '@angular/fire/firestore';
import { USE_EMULATOR as DATABASE_EMULATOR } from '@angular/fire/database';
import { USE_EMULATOR as FUNCTIONS_EMULATOR } from '@angular/fire/functions';

...

  providers: [
    {
      provide: AUTH_EMULATOR,
      useValue: environment.production ? undefined : ['localhost', 9099],
    },
    {
      provide: FIRESTORE_EMULATOR,
      useValue: environment.production ? undefined : ['localhost', 8080],
    },
    {
      provide: DATABASE_EMULATOR, // i.e., Realtime Database
      useValue: environment.production ? undefined : ['localhost', 9000],
    },
    {
      provide: FUNCTIONS_EMULATOR,
      useValue: environment.production ? undefined : ['localhost', 5001],
    },
  ],

我可以直接從environment.ts文件運行它而不會引發任何錯誤。

export const environment = {
    production: false,
    firebaseConfig: {
        host: 'localhost:8081',
        ssl: false,
        apiKey: '<api-key>',
        authDomain: '<project-id>.firebaseapp.com',
        databaseURL: 'http://localhost:9000?ns=<project-id>',
        projectId: '<project-id>',
        appId: '<app-id>',
        measurementId: '<measurement-id>',
    },
};

根據自 6.1.0 版以來的此文檔,您可以執行以下操作:

import { USE_EMULATOR as USE_FIRESTORE_EMULATOR } from '@angular/fire/firestore';

@NgModule({
  // ... Existing configuration
  providers: [
    { provide: USE_FIRESTORE_EMULATOR, useValue: ['localhost', 8081] }
  ]
})
export class AppModule { } 

版本 7

從版本 7 開始,您可以在模塊中使用這些方法

...
@NgModule({
    imports: [
        provideFirebaseApp(() => {
    
          const firebaseApp = initializeApp(environment.firebaseConfig)
    
          return (firebaseApp);
    
        }),
        provideAuth(() => {
    
          const auth = getAuth();
    
          if (!environment.production)
            connectAuthEmulator(auth, `http://localhost:9099`)
    
          return (auth);
    
        }),
        provideDatabase( () => {
          
          const db = getDatabase()
        
          if ( !environment.production )
            connectDatabaseEmulator( db, 'localhost' , 9000 );
    
          return ( db );
    
        } ),
        provideFirestore( () => {
  
          const firestore = getFirestore()

          if ( !environment.production )
            connectFirestoreEmulator( firestore, 'localhost' , 8080 );

          return ( firestore );

      } ) ]
      ...

根據Dev.to 的這篇文章,我設法設置了我的 Angular 8 應用程序,以與我模擬的 firebase 函數、firestore 和實時數據庫進行通信。

火力基地:

簡而言之:firebase 配置可能是在您的環境中設置的已注冊 Firebase 應用程序(projectId 等)的配置:`"firebase": {...actual firebase config here...}` 或通過 API 檢索。

請不要生產應用程序的前端公開您的API 密鑰和重要信息。

如何(對於那些沒有設置):可以在上面的文章或官方文檔中遵循模擬 Firebase: Setup Firebase Emulators , Run Functions Locally

角度:

以下是文章中關於Angular 的配置的片段。

src/environments/environment.ts

import {AngularFirestoreModule, SETTINGS} from "@angular/fire/firestore";

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [{
    provide: SETTINGS,
    useValue: environment.emulator ? {
      host: 'localhost:8080',
      ssl: false
    } : undefined
  }],
  bootstrap: [...]
})
export class AppModule {
}

src/app/app.module.ts

 import {AngularFirestoreModule, SETTINGS} from "@angular/fire/firestore"; @NgModule({ declarations: [ ... ], imports: [ ... ], providers: [{ provide: SETTINGS, useValue: environment.emulator ? { host: 'localhost:8080', ssl: false } : undefined }], bootstrap: [...] }) export class AppModule { }

src/app/app.component.ts

文章摘錄:

constructor(...
private app: FirebaseApp) {...}

...

ngOnInit() {
  if (environment.emulator) {
    this.app.functions().useFunctionsEmulator('http://localhost:5001');
    console.log('Using functions emulator');
  }
}

Vs:我實施的是:

 constructor(... private app: FirebaseApp) {...} ... ngOnInit() { if (environment.emulator) { this.app.functions().useFunctionsEmulator('http://localhost:5001'); console.log('Using functions emulator'); } }

文章中的注意事項適用於數據庫/ firestore而不是函數:

注意:其他 firebase 客戶端 sdk 的整體概念是相同的,但語法會在不同的實現之間發生變化。 主要目標是真正告訴firebase sdk,您想使用不同的url 來指向該服務。


Angular:為什么會這樣?

它允許您模擬多個環境,而無需更改您正在模擬的環境(文件)的基礎架構(不對本地主機進行硬編碼更改,而是應用程序本身會更改這些值)。

我建議僅將其用作模板並為您的應用程序自定義它 - 例如, app.modules中的localhost:8080可以是動態的並與環境變量相關聯以進行更整潔的配置。

對於使用沒有兼容模塊的 AngularFire v7 的人,您可以找到一個app.module.ts來使用模擬器。 我使用@amgular/fire v7.2.1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM