angular - 将默认的 Firebase 配置注入(inject) Angular 应用程序

标签 angular firebase

我需要为一个应用程序使用 firebase 托管的默认配置,因为我要将它部署到多个项目。

如果这是一个普通的 html 应用程序,您将使用:

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/6.1.0/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#reserved-urls -->

<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>

但是我正在使用一个 Angular 应用程序,所以我想将它注入(inject)到应用程序模块的初始化中。我试图做这样的事情:

let firebaseConfig = environment.firebase;

if (environment.production) {
  console.log('loading init');
  fetch('/__/firebase/init.json').then(async response => {
    firebaseConfig = await response.json();
  });
}

@NgModule({
  declarations: [
    AppComponent
  ],

  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(firebaseConfig),

这只是我的应用程序模块的一部分,但您可以大致了解一下。如果它在生产中,我想从 init.json 中提取它,但如果不是,我想从环境设置中提取它。

因为这是一个异步操作,我怎样才能让它工作?

最佳答案

您可以尝试以下选项:

app.module.ts

@NgModule({
  ...
  imports: [
    BrowserModule,
    AngularFireModule,
  ]
  ...

ma​​in.ts

import { FirebaseOptionsToken } from '@angular/fire';

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

function loadConfig() {
  return environment.production ?
    fetch('/__/firebase/init.json')
      .then(response => response.json())
    : Promise.resolve(environment.firebase);
}

(async () => {
  const config = await loadConfig();

  platformBrowserDynamic([{ provide: FirebaseOptionsToken, useValue: config }])
     .bootstrapModule(AppModule)
     .catch(err => console.error(err));
})();

关于angular - 将默认的 Firebase 配置注入(inject) Angular 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56431192/

相关文章:

node.js - 将 NodeJs 与 Firebase 一起使用 - 安全性

javascript - Firebase Web update() 删除所有其他子节点

javascript - Firebase 相关领域人口

java - FirebaseRecyclerAdapter 28.0

angular - 在组件测试规范中模拟 BehaviourSubject

html - 如何根据 body-tag 中的类设置嵌套 <div> 的样式

angular - 将管道添加到 Angular2 中的 formControlName

angular - ionic 2 : Change a sass variable dynamically

html - using/deep/in angular 4 component.css 导致其他组件使用相同的样式。如何解决?

string - Swift 2.0 字符串到 NSDate