我需要使用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>
但是我正在使用一个角度应用程序,所以我想在应用程序模块的初始化中注入它。我尝试做这样的事情:
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,
]
...
主目录
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));
})();