1
votes

I'm using TypeScript to implement firebase app, and there are four ways to initialize firebase app according to firebase documentation.

I'm successful when using firebaseConfig object, but using "Reserved Hosting URLs" I can't seem to get away from this message: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

What I'm doing is the following:

import * as firebase from 'firebase/app';
import "firebase/database";

... (inside of Component)

ngOnInit() {
  var testRef = firebase.database().ref('test');
  testRef.on('value', function (snapshot) {
    console.log('test', snapshot.val());
  });
}

I'm guessing that firebase.database() is likely getting invoked before firebase.initializeApp() code, but I can see that <script src="/__/firebase/init.js"></script> has been loaded successfully without an error, which contains the following:

if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
firebase.initializeApp({
  "projectId": "....",
  "appId": "....",
  "databaseURL": "....",
  "storageBucket": "....",
  "apiKey": "....",
  "authDomain": "....",
  "messagingSenderId": "...."
});

I've placed the <script src="/__/firebase/init.js"></script> in an appropriate place, in the body tag, as suggested by the documentation. Is there anything else I need to do additionally to make this work with TypeScript, and be able to use firebase.database() anywhere within the Component?

1

1 Answers

1
votes

You need to initialize Firebase before any other call to one of its component.

You may get the config from the reserved url in an async/await function like that:

const load = async () => {
   let config = {}
   const response = await fetch('/__/firebase/init.json')
   config = await response.json()

   ...

then pass the config object to initializeApp() and proceed with the rest of your app bootstrapping.