Skip to main content

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

Using Angular i18n translation strings outside templates

As of today in Angular 6 i18n is only available in the templates. So what if we want to use translated messages programatically and outside templates? I still use the component template html file to declare the message to be translated, but by obtaining the TemplateRef ViewChild in the component typescript file I can get the translated messages from typescript. <ng-template #boardInvitationEmailBody let-organization="organization" let-url="url"> <ng-container i18n>You have been invited to join the board portal for</ng-container> {{organization}}. <ng-container i18n> Please follow the link to: </ng-container> {{url}} </ng-template> So in the typescript code i can now call the createEmailBodyTranlated text method to get the translated text for use outside the template. @ViewChild('boardInvitationEmailBody') boardInvitationEmailBody: TemplateRef ; createEmailBodyTranslatedText(org...

Angular components not reloading on route change

Spent a long time wondering why route changes caused strange effects on my component, and found out that it was because my component wasn't reloading at all. I had this assumption that when a route parameter changed (e.g. /projects/1 changed to /projects/2 ) the component for the route would be reloaded. But this is not the default behaviour of the Angular router. The default behaviour of the Angular router is to reuse the route if the configuration is the same (and not reload the component). But we can override this by providing a RouteReuseStrategy to our @NgModule: providers: [ { provide: RouteReuseStrategy, useClass: AARouteReuseStrategy } ] The full custom implementation of the RouteReuseStrategy will then be like this (and it's the shouldReuseRoute method that changes the behaviour so that the component is reloaded on route parameter change): export class AARouteReuseStrategy extends RouteReuseStrategy { shouldDetach(route: ActivatedRou...

Conflicting styles with multiple Angular apps in the same page

About two years ago I was gradually converting an old web app to modern Angular. At some point the app was in a state were the Angular components were embedded as multiple apps at different locations in the page. Very soon I found that one app got the css styling rules from the other, and that the APP_ID that was supposed to be present in the generated html/css (according to the docs:  https://angular.io/guide/component-styles#inspecting-generated-css ) was not there. I made a fix for this, and a pull request to Angular and am very happy now see that my fix for this is finally included here So now you should also be able to use Angular for creating multiple standalone widgets, adverts in any web page that is not made in Angular. That could be news sites, blogs, portals or anything. Angular just got new significant areas of use