Simple Firebase service for Angular 2

If you want a very simple alternative to Angularfire you may create a firebase service very easily. I made this to avoid extra configuration when it comes to adding npm packages and configuring for bundling. This is done by downloading the scripts from Firebase CDN directly by using a dynamically created script tag.

Once the service is initialized you'll find the database in the public database property, and you just use the regular Firebase API. (Example: this.fbservice.database.ref('someproperty').set(somevalue) - and remember to have fbservice : FireBaseService in your component constructor to inject the service. )

And here's the code for the service:

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

declare const firebase : any;

const config = {
    apiKey: "",
    authDomain: ".firebaseapp.com",
    databaseURL: "",
    storageBucket: ".appspot.com",
    messagingSenderId: "",
  };
  
@Injectable()
export class FireBaseService {
    public database : any;

    constructor() {
        this.addScript("https://www.gstatic.com/firebasejs/3.7.4/firebase.js")
            .subscribe(() => { 
                firebase.initializeApp(config);
                this.database = firebase.database();
        });
        
        
    }

    private addScript(url : string) : Observable<any> {
        return new Observable((observer : any) => {
            let scr = document.createElement("script");
            scr.src = url;
            scr.onload = () => observer.next(); 
            document.documentElement.appendChild(scr);
        });    
    }
}

Comments

Popular posts from this blog

Create PDF's in Angular / Typescript

My VNC based development environment with Visual Studio Code running on Ubuntu

Angular 5 - Ahead of Time build configuration for rollup