如何在通过http调用获取配置后在angular 7中动态初始化firebase

How to initialize firebase dynamically in angular 7 after getting the configuration via http call

我正在尝试在使用@angular/fire 通过 http 调用获取配置文件后动态初始化 firebase。但所有文档和搜索都指向我在 app.module.ts 中初始化它,如下所示。

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        BrowserModule,
        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule,
        IonicModule.forRoot(),
        AppRoutingModule,
    ],
    providers: [
        StatusBar,
        SplashScreen,
        {provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
} 

是否可以像下面这样在任何服务中调用 initializeApp

@Injectable({
    providedIn: 'root'
})
export class FirebaseSyncService {

    constructor(private httpClient: HttpClient) {}

    initializeFirebase() {
        const url = 'http://localhost:3000/get-config?db=12345';
        this.httpClient.get<any>(url).subscribe(response => {
            AngularFireModule.initializeApp(response.config);
        });
    }
}

我不认为 AngularFire 有任何自己的配置,所以你可以只使用这里显示的常规 JavaScrip 初始化代码:https://firebase.google.com/docs/web/setup(select "from the CDN" 选项卡) :

// TODO: Replace the following with your app's Firebase project configuration
var firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

您需要确保 DEFAULT 应用在使用任何其他 Firebase 服务之前得到初始化。

经过多次拉扯后发现了一个简单的 hack。

我的environment.ts文件

export const environment = {
    production: false,
    firebase: getConfig()
};

function getConfig() {
    let config;
    let request = new XMLHttpRequest();
    try {
        request.open('GET', 'http://localhost:3000/index/get-config', false);  // `false` makes the request synchronous
        request.send(null);

        if (request.status === 200) {
            console.log(request.responseText);
            config = request.responseText;
        }

        return JSON.parse(config);
    } catch (e) {
        console.error('environment:getConfig: unable to get api key : ', e);
    }

    return config;
}

我的延迟加载模块导入:

@NgModule({
    entryComponents: [],
    imports: [
        BrowserModule,
        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule,
        IonicModule.forRoot(),
        AppRoutingModule,
    ],
})

下一步在服务或任何组件中,正常注入和使用

 constructor(private afs: AngularFirestore) {}

希望这对以后的任何人都有帮助。

对于那些在生产模式 (ng build --prod) 中构建项目有问题的人,您需要在提供程序中初始化 firebase,而不是直接在导入数组。

app.module(或您初始化 firebase 的模块)

 @NgModule({
     ...
 imports: [
   ...
   AngularFireModule, // do NOT initialize firebase here
   ...
 ],
 providers:[
  {
   provide: FirebaseOptionsToken, 
   useValue: environment.firebase  //initialize firebase from env here
  } 
 ]
  ...
})

environment.ts(与接受者答案保持相同的代码)

export const environment = {
    production: false,
    firebase: getConfig()
};

function getConfig() {
    let config;
    let request = new XMLHttpRequest();
    try {
        request.open('GET', 'http://localhost:3000/index/get-config', false);  // `false` makes the request synchronous
        request.send(null);

        if (request.status === 200) {
            console.log(request.responseText);
            config = request.responseText;
        }

        return JSON.parse(config);
    } catch (e) {
        console.error('environment:getConfig: unable to get api key : ', e);
    }

    return config;
}