3

Most of the suggestions are to do it in app.module.ts, right before @NgModule({}) (such as here or here or here or here or here) or to do it within the top level AppComponent's constructor. For example:

//app.module.ts
import * as firebase from 'firebase/app';
import { environment } from '../environments/environment';

firebase.initializeApp(environment.firebaseConfig);

The reason why I think it is a good approach is because I can have access to the same firebase instance from multiple services. However, despite having successfully using this method in 1 of my apps, I am not able to replicate the desire behavior from any other apps. Particularly, when trying to access the firebase instance from a service:

import { Injectable } from '@angular/core';

import * as firebase from 'firebase/app';
import 'firebase/auth';

const auth = firebase.auth();

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    constructor() {
        //Try accessing the current user, should return null or the user
        //It could be any function, I'm jusing using this as an example
        console.log(auth.currentUser);
    }
}

I always receive an error:

Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

What is the proper way to initialize firebase app so that all the services can have access to the same firebase instance? Preferably without relying on creating a new Service just to handle that.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
timthekoder
  • 415
  • 5
  • 16
  • It seems like the code in the second snippet doesn't import `app.module.ts`, which means that `firebase.initializeApp(environment.firebaseConfig)` doesn't run. – Frank van Puffelen Jul 15 '20 at 23:04
  • @FrankvanPuffelen: Thank you for the respond, but I'm still a bit confused. Isn't `app.module.ts` the top module that will be executed anyway (because it boots the app)? How exactly do I "import" `app.module.ts` in a service? I have never heard of it before. – timthekoder Jul 15 '20 at 23:29

0 Answers0