user3026206 user3026206 - 5 months ago 36
AngularJS Question

Adding Firebase authentication to angular-cli 2 app

this is a newbie question. I've worked through the Firebase tutorial for adding Google Authentication and that works fine. I've also worked through the angular-cli quickstart tutorial and that's also fine. However, in the Firebase tutorial, you add the authentication script (below) to the index.html page and in the angular-cli app, you're not supposed to modify the index.html file. So what's the best practice for where to put the Firebase authentication script?

<script src="https://www.gstatic.com/firebasejs/3.0.5/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com",
};
firebase.initializeApp(config);
</script>

Answer

If you don't want to change CLI file structure, you can download and add the script to angular-cli-builds.js -> vendorNpmFiles; add map/package info to src/system-config.ts:

/*******************************************************************************
 * User Configuration.
 *******************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
  'firebase': 'vendor/firebase.js'
};

/** User packages configuration. */
const packages: any = {
  // not sure if this is needed
  // or what type of module the file is...
  'firebase': { defaultExtension: 'js' } 
};

And then add the init code to main.ts:

// imports and stuff
...

import * as firebase from 'firebase';
// import 'firebase'; // or this?
bootstrap(AppComponent).then(() => {
    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
    var config = {
      apiKey: "apiKey",
      authDomain: "projectId.firebaseapp.com",
      databaseURL: "https://databaseName.firebaseio.com",
      storageBucket: "bucket.appspot.com",
    };
    firebase.initializeApp(config);
});

More info here: 3rd party lib installation.

Comments