How to use firebase.initializeApp (WITHOUT Angularfire) in Angular?

Viewed 440

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.

0 Answers
Related