WebCake

Not too long ago I wrote a post about getting Firebase installed in your Ionic 2 app. Well, last week Google had their I/O conference, which debuted the next major release of Firebase, v3, which comes with some significant changes. In this post, I’ll go through the same topics I covered in the first one, but this time using Firebase 3 methods.

This post has been updated and tested with the Beta 11 release of Ionic 2, and the RC4 release of Angular 2. Further updates to come.

If you’re interested in a demo, I’ve got one for each framework:

Installation

Originally I only had the CDN option. I’ve now updated this section to include a local installation as well.

Via CDN

I use this approach in the Angular 2 example I have listed above.

Much like with previous releases, you can install via CDN, using a script tag in your www/index.html file, or whatever main HTML file your application runs. So near the bottom, but before your build, and after any ES6 polyfills you might have, add this block:

<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script>
    // Initialize Firebase
    var config = {
        apiKey: <your-api-key>,
        authDomain: <your-auth-domain>,
        databaseURL: <your-db-url>,
        storageBucket: <your-storage-bucket>,
    };
    firebase.initializeApp(config);
</script>

If you’re not sure where to get that information, you can log in to your application dashboard, and click on the Add Firebase to your web app icon:

Screen Shot 2016-04-16 at 6.33.21 PM

That will bring up a modal that contains your config information.

Screen Shot 2016-04-16 at 6.33.21 PM

Once you have that in your main build template, your compiled application will have the firebase object applied to the window, available globally throughout your application.

Via Browserify

I use this approach in the Ionic 2 example I have listed above.

If you’re running an Ionic 2 project, as of (I think) Beta 5, Browserify comes built in as the package bundler of choice. If you’d like to use it to package in your Firebase files, that can certainly be done as well. Reading through the Firebase readme on NPM, I managed to get it working using the following steps.

First, use NPM to install Firebase, and save it to your package.json as a dependency:

$ npm install firebase --save

Now, open your app/app.ts, and import Firebase using the * as method:

import * as firebase from 'firebase';

With a reference to Firebase available in your startup class, you can initialize your Firebase application in your app’s constructor function:

// ...some other imports...
import * as firebase from 'firebase';

@Component({
    template: '<ion-nav [root]="rootPage"></ion-nav>'
})
export class MyApp {
    rootPage: any = TabsPage;

    constructor(platform: Platform) {
        const fbConf = {
            apiKey:<your-api-key>,
            authDomain: <your-auth-domain>,
            databaseURL: <your-db-url>,
            storageBucket: <your-storage-bucket>
        };
        firebase.initializeApp(fbConf);

        platform.ready().then(() => {
            StatusBar.styleDefault();
        });
    }
}

Note that I have Firebase initializing before the platform.ready() call. You’ll want to make sure Firebase is ready to go before any other application logic is loaded, so that you don’t thow exceptions when your app pages load.

Finally, since you now have Firebase as part of your build, you’ll want to reference it as a module where possible – e.g. as an import in any data services that make references to Firebase. You’ll see what I mean in the examples below, or if you check out data and user services in the Ionic 2 project I have linked above.

Typing Issues

You may experience typing issues. That is, when you try to compile, you may see this error:

app/data.service.ts(12,15): error TS2304: Cannot find name 'firebase'.

This is a matter of your TypeScript compiler not being able to find the typings associated with the firebase module. Some compilers don’t much care. However some do, and will exit your compilation process, preventing your app from building. Normally, you’d include a .d.ts file from DefinitelyTyped; but as of the time of this writing, the typings declared there only support Firebase 2.4.1. If you include those, you’ll see this error:

app/data.service.ts(12,24): error TS2339: Property 'database' does not exist on type 'FirebaseStatic'.

Obviously the interface has changed between versions of Firebase. So how do we get around this? You’ll need to install the updated typings, which are included in the NPM package. In the command line, run the following:

typings install npm~firebase --save

That should install it into the dependencies property in typings.json.

Next, you’ll notice there’s a new file added called typings/index.ts, with a reference to the Firebase 3 typings. That’s not what you want. Instead you’ll add your new reference to typings/main.ts. Looks like this:

/// <reference path="main/ambient/es6-shim/index.d.ts" />
/// <reference path="modules/firebase/index.d.ts" />

Awesome. Now you should be able to start your application, and in compiling your TS you shouldn’t have any errs.

Side note on TypeScript

You should also be aware that many base projects (such as, at the time of this writing, the Angular 2 Quickstart) come with a default typings config that disallows implicit any types, and will throw errors during compilation unless every variable declared has a type. If you’re not a fan, you can change the property in your tsconfig.json:

"noImplicitAny": false

Syncing Data

The core difference with the new release of Firebase is the breaking up of the main services into their own separate classes. In Firebase 2.x, all of the functionality was part of a flat object full of methods. That’s changed, and such things as firebase.auth and firebase.database have now been broken apart. In fact, you can find all of the methods are now classified, which makes sense now that so many more features have been added.

So, as with any application, the next thing we’ll do is set up a data service. This is actually a very simple process if you already have an app running on Firebase 2.x, and still simple enough if you’re starting a fresh project.

Database references

Since Firebase works off of reference locations of data, and then child-references based on a hierarchical structure, we can set our initial data point t the root of our synced database:

import {Injectable} from '@angular/core';
// if you've gone with the local installation approach, you'd use the following:
import * as firebase from 'firebase';

@Injectable()
export class DataService {
    public db: any;
    constructor() {
        this.db = firebase.database().ref('/');
    }
}

Why does that work? If you noticed above, in the config object we pass to the firebase.initializeApp() method, we already listed the URL to our database. Once that was initialized, the firebase.database() method returns a reference to that database. The ref('/') method just indicates that this.db is going to point to the root of that database’s JSON tree.

To use it, simply inject your data service into whatever class you’re developing:

// other imports...
import {DataService} from '../../../../data/data.service';

@Component({
    templateUrl: 'build/pages/history/pages/day/day.html',
    // you'll likely have more properties here...
    providers: [DataService]
})

export class Day extends LoadingPage {
    // skipping over some initial property declarations
    constructor(private _data: DataService) {

    // ionViewWillEnter is also specific to Ionic 2,
    // so if you're in Angular 2, you'd import and use ngOnInit()
    ionViewWillEnter() {
        // DATA SERVICE IN ACTION
        this._data.db.child('staticData').on('value', data => {
            this.staticData = data.val();
        });
    }

}

So notice that in this case, I’m hitting the staticData property of my JSON tree, a top-tier property that has its own branching hierarchy underneath it. If I were to write that location as a URL, it would be https://burning-fire-5659.firebaseio.com/staticData.

But hey, you can go deeper into your JSON when you establish your data service. Let’s say you have a complex database that has multiple top-tier properties. Instead of returning one property that exposes the entire database, you can return multiple properties that return multiple branches of your database:

import {Injectable} from '@angular/core';
// if you've gone with the local installation approach, you'd use the following:
import * as firebase from 'firebase';

@Injectable()
export class DataService {
    public events: any;
    public units: any;
    public tasks: any;
    public parts: any;
    constructor() {
        this.events = firebase.database().ref('/events/');
        this.units = firebase.database().ref('/units/');
        this.tasks = firebase.database().ref('/tasks/');
        this.parts = firebase.database().ref('/tasks/parts/');
    }
}

For my purposes, I simply left my data service pointing to the JSON root, since I don’t have a lot of complex data. On that note, let’s move on to users.

Users in Firebase

When I posted about integrating Firebase 2.x into your application, I explained a user service as a way to implement your data service. Since Firebase 3 breaks user authentication out of the data syncing workflow, I figure it’s best to cover that separation here, and show how I was able to get authentication working, while still utilizing the user data I had in my database.

Refresher on users in Firebase

Firebase comes with a user authentication workflow, but that doesn’t mean it necessarily is meant to store all of your users’ information. The Firebase User interface has a limited set of properties available, which are generally filled out by the application during sign up or changes to the user’s settings. As the docs say:

You cannot add other properties to the Firebase User object directly; instead, you can store the additional properties in your Firebase Realtime Database.

So if you want to expand on those properties, you can use the user’s uid property to create a place for them in your database, probably under a top-tier property in your JSON tree called users. Each user would then be identified by their uid, which you can grab during the authentication process, or by calling the currentUser method on the auth class.

That being the case, here’s what my users object looks like in my JSON tree:

// base of my JSON tree:
{
    users: {
        some_uid_1: {
            settings: {...},
            profile: {...},
            activity: {...}
        },
        some_uid_2: {
            settings: {...},
            profile: {...},
            activity: {...}
        }
    },
    staticData: {...},
    anotherProperty: {...},
    yetAnotherProperty: {...}    
}

Extending the data service for users

So now, based on what we’ve done above, we can do two things:
1. we can set an auth property on our data service that stores the return of the Firebase auth method
2. we can set a users property on our data service that references the users branch in our JSON tree.

NOTE: You could very easily break auth into a completely separate service. For my purposes, this works since my app was built on Firebase 2, where all of these methods were integrated; but if you think it’s a bad idea then feel free to disagree.

Here’s what that looks like:

import {Injectable} from '@angular/core';
// if you've gone with the local installation approach, you'd use the following:
import * as firebase from 'firebase';

@Injectable()
export class DataService {
    public db: any;
    public auth: any;
    public users: any
    constructor() {
        // still pointing to the base,
        // so that I can access other parts of my tree
        this.db = firebase.database().ref('/');

        // now adding a shortcut to hit the
        // users branch of my JSON tree directly
        this.users = firebase.database().ref('/users');

        // as well as adding a reference to the Firebase
        // authentication method
        this.auth = firebase.auth();
    }
}

With all of that in place, we’re set for anything that might involve a combination of data stored in our database, and user authentication – so anything that might be considered user-specific. In my application, that means keeping track of users’ daily diet intake, their settings for intake targets, and diet history and reporting.

97 responses to “Using Firebase 3 in Angular 2 and Ionic 2”

  1. Anubhav Berry says:

    thanks for writing this up. I have 1 question though: the firebase object in the DataService is not recognized. Since you’ve initialized the app in index.html, the firebase object is available in the html. The DataService does not recognize the reference to firebase. Is there anything else you did to make it work.

    • Colin says:

      Hell, I’m sorry homey-san. I forgot the call to the CDN to actually get Firebase in the HTML snippet. I’ve updated it above. Here’s what my body looks like in index.html:

      <body>
      
        <!-- this Ionic's root component and where the app will load -->
        <ion-app></ion-app>
        
        <!-- cordova.js required for cordova apps -->
        <script src="cordova.js"></script>
        <!-- Polyfill needed for platforms without Promise and Collection support -->
        <script src="build/js/es6-shim.min.js"></script>
        <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
        <!-- Firebase CDN -->
        <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
        <script>
            // Initialize Firebase
            var config = {
                apiKey: "myApiKey...",
                authDomain: "burning-fire-5659.firebaseapp.com",
                databaseURL: "https://burning-fire-5659.firebaseio.com",
                storageBucket: "burning-fire-5659.appspot.com"
            };
            firebase.initializeApp(config);
        </script>
        <!-- Zone.js and Reflect-metadata  -->
        <script src="build/js/angular2-polyfills.js"></script>
        <!-- the bundle which is built from the app's source code -->
        <script src="build/js/app.bundle.js"></script>
      </body>
      </html>
      

      You’re right that the TypeScript compiler, and any IDE worth its salt will tell you that it can’t find module firebase, but it should still work. There’s probably a very TypeScripty way around that, but I’m still new to TS so I’m not sure what it is. I’m hoping that when the DefinitelyTyped Firebase file gets updated it’ll help solve the problem.

      But in regards to your point about loading it in the HTML vs. the DataService – it should still work, since ultimately all we’re doing at the end of the day (however fancily) is loading JS into a rendered HTML file. At least, that’s what it looks like from where I’m sitting. So as long as something’s available to the global scope – which firebase is once it’s loaded from the CDN – it’ll be available to anything loaded thereafter. Same as you might remember from the olden days of jQuery.

      If that doesn’t work, would you mind pushing up a branch so I can help you take a look? I’d love to know if I’m missing something.

      • slvn says:

        Hi there, I was facing the same TypeScript compiler error but managed to overcome it by setting “noEmitOnError”: false such that ng cli will not throw compilation error.

        Result: The page is able to load without any errors.

        • Colin says:

          Awesome. I didn’t know you could do that. Ideally, I’d like to notify the compiler that firebase is in fact going to be in the DOM and prevent it from throwing that way. But this is a first step. Appreciated!

          • I’ve been trying to figure out the same thing. I’m using “import * as firebase from ‘firebase’;” and call firebase.initializeApp(config) in my app.ts file. I’m able to connect to my firebase & implement it properly, but the compiler is still giving me this error: “TypeScript error: app/app.ts(5,27): Error TS2307: Cannot find module ‘firebase’.” – is there anything I can do to fix this? Thank you!

      • saurabh vyas says:

        Hi I have 2 providers (auth provider and data provider) in my ionic2 project, auth provider works perfectly but the data server isnt , When I call the getdata method I am always getting junk/garbage data “Object { A: Object, W: Object, g: Object } ”
        Can you please help?

        • Colin says:

          Hey, so I’ve seen that before, and it’s the internal (probably minified/uglified) connection details for your Firebase instance. So you’re definitely connected. A couple debugging points I’d recommend:

          • make sure your data permissions allow your data to be seen at whatever auth level you’re in when you try to display that data
          • make sure you’re treating the connection like an async data stream by subscribing to the data event, and passing back the value
          • watch for explicit function() statements within your class and make sure your this scoping isn’t getting messed up.

          I’d also be happy to help you debug further if you’d like to post your class methods here, send a link to a pluker, or point me to a branch on GitHub

    • Colin says:

      Ok so did some digging, and it seems Android doesn’t natively support the some aspect of ES6/15 that the Firebase library uses. Based on the error thrown, it looks like it’s either Symbols or Iterators. So once I move the CDN script past the already-included build/js/es6-shim.min.js script, I can launch the app no problem, and all is gravy. I’m going to updated the snippet above for any wayward travelers who happen upon this blog post and only read the markup without reading through all of the comments – which I used to be super guilty of. I’m also putting together a list of debugging steps that might help others as they hit problems getting up and running.

  2. tomas says:

    Hello
    Thanks for your post.
    My ionic 2 app with firebase 3 works at mobile web. but does not work at android.
    Please help me.

  3. zozourban says:

    Thanks for this tuto !

    One question, how we can implement Notification push system with new Firebase ?

    Thanks in advance

    • Colin says:

      You’d have to integrate those using the native code. I personally haven’t ever gotten into any Notifications service, so I wouldn’t know any further details; but you could explore the native Push plugin that’s documented on the Ionic 2 docs as a starting point. From what I’m seeing in the Firebase docs, they really want you to integrate Notifications using one of their native SDKs, which rely on Firebase being installed natively as well. In theory, you could have a Firebase reference in your webapp for your database and auth, and another Firebase ref in your iOS or Android code for push notifications, but that seems messy.

      I’ll also point out that Ionic Platform supports push notifications, and might be a bit easier to integrate; again, since I’ve never explored it, that’s just a guess.

      • zozourban says:

        I saw for ionic push, but it’s i would like somethink like this : Firebase has value, when this value is same like another, firebase send a push notification on the/all ionic apps. it’s possible to do this ?

        • Colin says:

          It might be. Like I said I don’t have experience with programming push notifications, so this is only conjecture. But I do believe you have a couple of options. You could certainly get into the native Firebase SDKs to try to pull in messaging that way; so that’s one option. Alternatively, you could set up a micro-service in a cloud platform (e.g. Heroku) that has admin access to your Firebase database, and listens to changes as they stream in. When those changes meet certain conditions it could post messages to a Notifications service like Onseignal, Urban Airship, or Ionic Platform to notify specific users. Again, wiring in those notifications services is going to either involve a plugin like Push, or writing some native code. It’s not as smooth and requires probably more overhead than you’re looking for, but it’s an option. Since I don’t know much about them, that’s the best I’ve got.

  4. Lucas Ávila says:

    Colin, would you have a demo of this? Could you share it?

  5. iamDoerr says:

    Hello Colin, thank you for sharing this tutorial

  6. Lucas Ávila says:

    Colin, I’m trying to ship firebase without the CDN but I can’t get it to work.
    How would you suggest I do it?
    Why did you go the CDN way instead of putting it in the app?

    • Colin says:

      For me, it was a matter of simplicity. I wanted to get my app out the door as soon as possible so I could get it in my users’ hands, and the CDN way allowed me to do that. Ultimately I’d prefer it to be in the app, as part of the build, but that was something that I planned to do later. Since I haven’t tried it yet, this is just speculation. But I’d imagine you have two options. The first would be a local file that you pull in through a script tag, in place of the CDN link. I’d imagine you’d have to leave it in your www/build/js/ folder and link it from there, so that it’s not part of the build. The second option would be to make it part of the build, in which case I’d imagine order of inclusion would be a big deal. Ionic switched to Browserify in one of the recent Beta releases. I havne’t yet done any research there, so I don’t know much about configuring it. But it looks like you would edit the gulpfile.js, changing the options in the buildBrowserify task, and possibly extend its browserifyOptions with some of Browserify’s native options. I’ll probably take a look this weekend, and if I find something that works I’ll write it up. UPDATE: ignore most of this comment. The post has been updated with local file instructions.

  7. Hey, how do you make sure the data is ready to render to the page? I’m trying to do this but when I do something like this.staticData = data.val(); I run into a problem.

    Rendering {{staticData | json}} renders the json tree to my page

    But rendering {{staticData.anyProperty}} I get an error saying it can’t find ‘anyProperty’ of undefined.

    So I’m guessing my problem is with async, staticData is just not ready when {{ staticData.anyProperty }} tries to make the call

  8. xap5xap says:

    Man, thank you. I was trying to achieve this, with no luck. Finally, I found this post. Thanks for sharing

  9. Lucas Ávila says:

    I could come up with a quickfix. It’s almost what Colin said to do, but instead of putting firebase.js inside the build folder in www folder I left it at the root and just import it like this in index.html. This way the .js is not deleted every build.

    // Initialize Firebase
    var config = {…
    };
    firebase.initializeApp(config);
    // firebase.database.enableLogging(true);

    It’s not a perfect solution as typescript still can’t work with it (it gives me errors telling that cannot find name firebase), as expected.

    • Lucas Ávila says:

      The actual import code:
      script src=”./firebase.js”

    • Colin says:

      That’s a studly solution. Going to update my app for the next release. Thanks man!

    • Colin says:

      I was messing around with it this morning and was able to include it in the build using Browserify. I’ve updated the post above if you want to try it out. TypeScript still yells at me, so I don’t know that this solution is any better either. I’ve also updated it in the GitHub project if you want to take a look there.

  10. phpcoder says:

    Hi Colin. The whole point of Ionic 2 is to build apps for Android, iOS etc. By following your tutorial i get WSOD on Android. It says “ORIGINAL EXCEPTION: ReferenceError: firebase is not defined”. So what is the point then to use firebase like you suggest? (i tried to put firebase.js to www/build/js, but error is the same). Is it because firebase object is only awaylable on window object in the browser? Any solutions to this problem, anybody?

    • phpcoder says:

      update: i was not 100% correct, as far as i see for some reason firebase is not recognized only when i try to use it inside my custom service. Just tested a dummy app which simply loggs in using firebase, and since i’m using “firebase” object directily in a Page component, instead of accessing it via my specific/custom FirebaseService where i previously tried to access firebase object, it works fine. So the question is – how to access firebase object from within a service and how to use offline version of firebase.js? As far as i see it is deleted from www/build/js folder, so probably it’s not a good idea to just throw it there..

    • Colin says:

      If you pull the GitHub project I have linked at the top of this post, it does all of the things you’re looking for: runs in iOS and Android, includes a local copy of Firebase, and calls Firebase in services instead of directly in pages or components.

      • phpcoder says:

        Thanks for your effort! Another question is firebase usage in Angular 2. I’m trying to use it as you do in your tutorial. The problem is that server won’t start (because of a lot of ERR on “npm start”) when i try to use firebase object. The only current workaround i use is i start the server first, then i add the code which uses firebase obj and then it works. But i have to do it over again if i stop the server. Any solutions to this? I’m using all the latest nodejs + npm and latest quickstart-based version of the angular 2.

      • phpcoder says:

        Did you try your own angular2 tutorial? It doesn’t work. Just try to create a simple app out of quickstart application cloned from github. Then just add your data.service.ts file (you can keep only db variable for the sake of simplicity) and import it from app.component.ts. Now “npm start” = crash. I mean what is the point?

        • phpcoder says:

          And yeah, of course i’ve added required javascript to index.html (2 script tags like in your example with my config data). Any comments/suggestions on this?

          • Colin says:

            Could you be a bit more clear on the error you’re seeing and the steps I need to take to reproduce the problem? Maybe paste the stack trace? Or push up a branch that I can take a look at?

      • phpcoder says:

        The simplest scenario is this: can you successfully start the server using exactly the same code as you provide here in your angular2 tutorial? For whatever reason, as soon as i use “firebase” obj in my code, the server won’t even start. For example this: this.db = firebase.database().ref(‘/’); already crashes when i do “npm start”:

        $ npm start

        angular2-quickstart@1.0.0 start c:\xampp\htdocs\myapp
        tsc && concurrently “tsc -w” “lite-server”

        app/data.service.ts(7,19): error TS2304: Cannot find name ‘firebase’.

        npm ERR! Windows_NT 10.0.10586
        npm ERR! argv “c:\Program Files\nodejs\node.exe” “C:\Users\admin\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js” “start”
        npm ERR! node v4.4.5
        npm ERR! npm v3.8.7
        npm ERR! code ELIFECYCLE
        npm ERR! angular2-quickstart@1.0.0 start: tsc && concurrently "tsc -w" "lite-server"
        npm ERR! Exit status 2
        npm ERR!
        npm ERR! Failed at the angular2-quickstart@1.0.0 start script ‘tsc && concurrentadmin@OR-PC /c/xampp/htdocs/myapp (master)

        Let’s say this is the only line where i try to use “firebase”. If i comment it, then the server starts normally.

        • colinjlacy says:

          Ok, that helps a lot. In answer to your question, yes I can run it as it’s written. But I’m more interested in why you can’t. Tonight after work I’ll dig into it. At first glance, it looks like it’s a setting in the .tsconfig that comes with the angular2-quickstart project causing it to abort on compilation error. I’m not using that project as a base, so I don’t have the same configurations you might have. But I’ll try and duplicate and update the post with a solution once I find it. Thanks for bringing it to my attention; I’d imagine other people will have the same problem so I’m happy to get it resolved as quickly as possible.

        • Colin says:

          Hey man, I’ve updated the post with info on how to tackle this. It’s a matter of the TypeScript compiler tsc aborting on error. Until there’s an updated firebase.d.ts available, this seems to be the best option. Thanks again for pointing it out!

          • phpcoder says:

            Thank you very much!!! I’ll try it. I’m still a big newbie in angular2 and Ionic 2 worlds, so it helps a lot get get feedback like this!

  11. Rhea Dimayacyac says:

    any one can help me in uploading audio in firebase storage please

    • henrysplaces says:

      Thanks for the firebase example on plunker.co. One question, how secure is the login? Pardon my ignorance, but would it not be easy for someone to amend the client side code i.e. the part that is

      <

      div *ngIf=’isAuth’> and get access?

      • Colin says:

        In terms of the template being displayed, then yes. In terms of the data being displayed it depends on the Firebase database rules. I’ve strengthened my database security so that you won’t be able to see that data if you aren’t logged in; so now if you try it, you’ll just see the template message and no data.

      • Colin says:

        good catch, btw.

    • Colin says:

      I haven’t tried storage yet. Can you give some info as to what you’re specifically having trouble with?

  12. Hi Colin,

    First of all, thanks for this post… It was the most complete post about Ionic 2 + Firebase 3 that I had found.

    Second, I’m trying to make the social login (Google+ and Facebook) with Ionic 2 + Firebase 3, but I’m having some problems with it.
    Have you ever done the integration with any social login?

    • Colin says:

      No worries. I haven’t tried any social integration yet, and the app I have out now won’t have it. But I’ve cut my last feature release on that one, and I’m in sprint 0 on the next, which will definitely have at least Facebook login. Should be working on that some time two weeks from now, depending on how sparring, fishing, and Dark Souls affect my free time. Once I have it working I’ll write about it.

      • RaulGM says:

        Great post, Colin! Thank you very much. I have a question, I read in one of the comments that you would do a login with Facebook post. When is that post is gonna be online? I want to do that with Firebase, Ionic 2 but don’t find enough documentation out there. That would be a great post!! Thanks a lot!

        • Colin says:

          Yes, I’ll probably tackle that during my Christmas break. Right now I’m trying to catch everything up to Ionic RC2, starting with this post. Once I have that done I’ll go back to writing new content.

  13. Sasha says:

    Hi Collin! I’m programming an app using firebase v3 and ionic 1, but your tutorial is about ionic 2, i’ve been researching and it seems that ionic 2 is still unstable. What do you think? Any tutorial about Firebase v3 and ionic 1???? Thanks a lot!

    • Colin says:

      Unfortunately no. You’re certainly right, Ionic 2 has left me with plenty of beta-upgrade headaches. But I’ve spent all of my time learning the new frameworks; I haven’t dabbled with Ionic 1 in almost two years.

    • Ben Richter says:

      Sasha —

      Did you find anything for Firebase3 and Ionic 1? Have you had any problems with compatibility?

      Ben

  14. daleflowmoco says:

    Hi i tried you ionic 2 demo and I’m getting the same issue as my own project where by app.bundle.js is not created. is this because the ts compiler freaks out with “cannot find module firebase”?

    • Colin says:

      This seems to be a common problem that’s popping up more frequently. In my experience, the TypeScript compiler hasn’t escaped on error, but that could have been updated in recent releases of Ionic. I’ll be looking into it tonight to see if I can resolve it. Also, on the GitHub project I have listed above, one of the issues listed seems to have addressed this. The poster opened and closed it before I could take a look.

    • Colin says:

      I’ve updated the post with a quick fix on how to handle this. The main problem is that the firebase.d.ts typings available aren’t updated for version 3 yet; until that happens, tsc will throw. The solution posted above is a workaround, but ultimately the right solution will be to include typings once they’re available.

      • Hey Colin,

        As everyone is saying above, great tutorial to a grey-area issue in these times of beta frameworks and libraries around Angular/Ionic 2, really clear stuff!

        I am having a similar problem to Genaro, TSC throws an error saying:

        TypeScript error: app/app.ts(12,27): Error TS2307: Cannot find module ‘firebase’.

        I understand that the typings have not been completed for Firebase v3 yet, but the

        declare var firebase: any;

        method doesn’t stop TSC from throwing the error every time. Am I missing something? I have not included the Firebase CDN on index.html as I’ve used npm to install so it should be available.

        Any help would be great, Thanks!

        Darragh

        • Colin says:

          I’m not sure why you’d still get that if you’re declaring firebase as any. In this case I don’t think the way you’ve installed it affects compilation, although I could be wrong about that. Is there a branch you can push up so I can take a look? Or maybe give me some steps to duplicate?

        • Hi Darrag, Colin,

          I was moving “firebase.initializeApp(config)” on different places, I was trying to apply dependency injection approach of angular2, where object creation must occurs once (, unsuccessfully.

          Meanwhile, the way that I solved, is using a global variable to get and use the reference of firebase database instance.

          STEP 1.

          In apps.ts, creating the firebase instance

          import {DataService, fb} from ‘./lib/data.service’;
          :
          :
          export class MyApp {

          private rootPage:any;

          constructor(public _data:DataService, private platform:Platform) {
          this.rootPage = TabsPage;

          STEP 2.

          on data.service.ts, get the reference of firebase database in global var “fb”

          import { InAppBrowser } from ‘ionic-native’;
          declare var firebase: any;
          export var fb:any
          :
          :
          firebase.initializeApp(config);
          this.auth = firebase.auth();
          this.db = firebase.database();
          fb = this;

          STEP 3.

          and then use the reference, by example on contacts.ts

          import {DataService, fb } from ‘../../lib/data.service’;
          :
          @Component({
          templateUrl: ‘build/pages/contact/contact.html’
          })
          export class ContactPage {
          public users: Observable;
          public usuarios : Observable<{}>;
          public _data: DataService;

          constructor() {
          this._data = fb;
          }

          Here is the complete project: https://github.com/genaromendezl/ionic2-firebase3-multi-Auth.git

          Also, I solved the problem causing “firebase not found” error, just installing

          “sudo typings install –save –global firebase”

        • RODRIGO MACHADO says:

          This helped me out with the 2307 error: https://forum.ionicframework.com/t/cannot-find-name-firebase/46839
          Although is not the exact same error, it did the trick.

      • Aaron Saunders says:

        the typings are updated, just in the wrong place…

        add this to main.d.ts

        ///

        • Colin says:

          Hey man, could you be a bit more specific? If the typings are updated, are they in a place where we might be able to access them?

  15. I have been working well with firebase 3 and ionic 2, and initializing and connect succesfully with my database, and display data, but it only works once. If I try to open a second page, DataService class’s constructor, call to firebase.initializeApp again and my app stop working. Is there any other way to avoid this?

  16. CJ says:

    Hey, is there a .js version of this? I have already made my app in Es6/ionic2 and I’m not trying to switch over to typescript. Someone please help

    • Colin says:

      Hey buddy, there might be resources elsewhere; but on my blog I’ll generally only focus on TypeScript. Since converting I’m seeing the advantages in projects that include it, and missing it when working on projects that don’t. That being said, a lot of the concepts should translate over pretty well. While I’m not familiar with the ES6 setup of Angular 2 (and therefore Ionic 2), I would think that most of the straight JS bits should translate over nicely. At any rate, best of luck to you.

  17. lola says:

    I am installing firebase with “npm install firebase –save”

    I get:
    D:\priv\Dropbox\pub\rnd\ionic\app2tut>npm install firebase –save
    npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
    npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14
    npm WARN enoent ENOENT: no such file or directory, open ‘d:\appp2tut\node_modules\validate-npm
    -package-license\package.json’
    npm WARN app2tut@1.0.0 No repository field.

    I even did an npm install at the main app dir, still no go…any idea ?

    • Colin says:

      Never seen that before. I’m not a Windows guy so I wouldn’t know if there are any quirks about some of the dependencies with the way some of those packages are installing. Sorry I can’t be more help there.

      • lola says:

        yeah even I hate it when apps made for linux are made window-able (like git/docker/node) and always have some kink or the other in getting it to work. will go back to linux too.
        Thanks for the update !

  18. lola says:

    ‘nother question: in the i2 getting started docs, they have:

    @Component({
    templateUrl: ‘build/app.html’
    })
    class MyApp {
    constructor() {
    }
    }

    whereas you have:

    @App({
    template: ”,
    config: {}
    })
    export class MyApp {

    which format is right (for i2) or what’s the diff ? Thanks in advance !

    • Colin says:

      Use @Component. It used to be @App in a previous beta release, but it looks like they removed that annotation. I’ll update my post.

  19. lola says:

    Hi Colin, could there be something missing in your instructions – I am following your instructions for db connectivity and I get these errors:

    TypeScript error: /home/cos/app1/app/data/data.service.ts(3,27): Error TS2307: Cannot find module ‘firebase’.
    TypeScript error: app/app.ts(6,16): Error TS2304: Cannot find name ‘require’.
    TypeScript error: app/app.ts(7,1): Error TS2304: Cannot find name ‘require’.
    TypeScript error: app/app.ts(8,1): Error TS2304: Cannot find name ‘require’.

    On googling, I found that typings had to be installed and each guy has some funky options or the other http://stackoverflow.com/questions/31173738/typescript-getting-error-ts2304-cannot-find-name-require

    Have you installed typings ?

    I tried installing typescript2 (per that url), that didnt help either

    You mention browserify is already in ionic2 but it isn’t
    Even after manually installing browserify I get the same errors

    Seems like ‘require’ can be satisfied by either typings or browserify and is just adding to the confusion of too many tools doing the same thing in a million different ways.

    I did install firebase to npm like so:
    $ npm install firebase –save
    app1@ /home/cos/app1
    └── firebase@3.2.1

    npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
    npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14
    npm WARN app1@ No repository field.
    npm WARN app1@ No license field.

    Any suggestion on whats missing will be a big help..thanks !

    • Colin says:

      Hey Lola,

      Regarding require, I haven’t used it in any Angular 2 or Ionic applications; that said, I’d imagine the link you said should work for adding typings to get it operational. Is there a reason you’re using require instead the import syntax?

      As far as the ts compiler not being able to find the module – this feels like a dumb question but are you sure it installed correctly? If you open node_modules do you see a firebase folder? Sorry, I generally start with sanity checks when things that should work don’t work. Next step would be to see if there’s something different between your project and the one I’ve put up. Would you mind sharing a link to a repo?

      • lola says:

        “If you open node_modules do you see a firebase folder “=> yes

        I did have the import but it gives this error: …seService.ts(3,27): Error TS2307: Cannot find module ‘firebase’.

        I did confirm I had installed fb, installed it again anyway, got some warnings and confirmed installed version was 3.0.4

        so i googled other ways to do it and hit a browserify way to do a require. guess i got two blogs mixed up.

        Regarding the link to a repo, I dont have one online and all I am trying to achieve is to fb’ify the tutorial template with ionic2/fb3

      • lola says:

        You mention browserify but I dont see it being used. I thought the main advantage of it was we can use require();

        Even in the link you pasted on browserify/npm/fb they have var firebase = require(‘firebase’); and they dont have any import statements at all.

      • lola says:

        Now I am reading that “Firebase Storage is not included in the server side Firebase npm module. Instead, you can use the gcloud Node.js client.” and we should use gcloud instead….aaaargh…

        • Colin says:

          yes, that sound. this is obviously very frustrating for you and I’m sorry I haven’t been able to point you in the right direction yet. In the update to Beta 4 they made the change to include Browserify in the starter templates. So if you’re not using one of those, then it might explain why it’s not working for you. I haven’t done much digging yet to see if they’ve removed it. I’ll be honest, this is my second week in a row traveling for work and I’m not getting as much time at my computer as I’d like.

          When i said default i meant the import * as firebase from 'firebase' syntax that I had listed. Browserify, from my understanding, is a package tool that allows you to bundle packages in the front-end as you would in the backend, e.g. a Node project. So yes, you can pull modules like you would in Node, but in this case your TypeScript compiler is yelling at you before you even get to require. You can also you the import syntax.

          As another quick sanity test, can you pull the GitHub project I have linked and see if you can get it to work?

          • lola says:

            I have everything latest (& beta lol), but your statement about TS makes sense..will look more into that.
            I thought TS would be included in fb-tools (if not, why not 😉

            (Also as I had seen in other blogs, I had asked earlier if you explicitly installed typings and then typings install firebase – this seemed like an older workaround to me, not mentioned in v2 nor fb3 docs at all) (https://firebase.google.com/docs/server/setup)

            Too bad v2 docs have zilch about backend interaction.

            I did think of pulling your code down, I will soon, but my game plan was to have a very simple db setup. (And I am glad you aren’t including AngularFire as some other bloggers are suggesting, even for a simple DB setup)

            From what I understand about Browserify as a packaging tool, we do not need imports anymore, just require. Need to poke around a bit more with this. Cheers !

  20. lola says:

    the versions I have are:

    [cos@localhost ~]$ firebase –version
    3.0.5

    [cos@localhost ~]$ node –version
    v5.12.0

    [cos@localhost ~]$ ionic –version

    2.0.0-beta.35

    and when I run your app I got the same:

    TypeScript error: /home/cos/firebase-ionic-2-demo/app/data/data.service.ts(5,27): Error TS2307: Cannot find module ‘firebase’.
    TypeScript error: /home/cos/firebase-ionic-2-demo/app/user/user.service.ts(5,27): Error TS2307: Cannot find module ‘firebase’.
    TypeScript error: app/app.ts(4,27): Error TS2307: Cannot find module ‘firebase’.

    So I was forced to replace imports with the declare var

    No compile errors, but runtime error:

    ReferenceError: firebase is not defined
    at new MyApp (http://192.168.224.182:8100/build/js/app.bundle.js:24:9)

    as it removed that dummy declaration during compile

    I installed typings per http://mhartington.io/post/ionic2-external-libraries/ just to see if it would make a diff it didnt

    also, just fyi, on your git repo, instead of asking others to do a pull, they could just do a clone and everything will be brought down as it is on your local.

    • Colin says:

      OK homey-sama, got it working. You were right, my solution in my app no longer works. Not sure when that happened, but thanks for letting me know. I’ve updated my app, so if you pull it, install Node modules, and run to a platform, it should work. Steps I took:

      Make sure you’ve installed Firebase 3 via NPM. Then in the command line, run the following:

      typings install npm~firebase --save
      

      That should install it into the dependencies property in typings.json.

      Next, you’ll notice there’s a new file added called typings/index.ts, with a reference to the Firebase 3 typings. That’s not what you want. Instead you’ll add your new reference to typings/main.ts. Looks like this:

      /// <reference path="main/ambient/es6-shim/index.d.ts" />
      /// <reference path="modules/firebase/index.d.ts" />
      

      Awesome. Now you should be able to start your application, and in compiling your TS you shouldn’t have any errs.

      I was able to confirm that Browserify is indeed packaged into the Ionic build, at least as of Beta 7. Do you know which release you’re using of ionic-angular? It’ll be in your package.json. The version you have above is for your Ionic CLI tool.

      Once I’ve been able to test and confirm these steps with the latest Beta, I’ll update the blog post.

  21. Sagar says:

    Firebase 3.x methods signInWithRedirect and signInWithPopup don’t work on mobile when implemented as an ionic app. Any fix for this other than using some other plugin?

  22. Abraham Pineda Zelaya says:

    Colin!!!

    You are a freaking genius!! I been fighting with this Sh*^^& fr days!!

    Indeed is the solution.

    It works with Ionic 2 + Firebase.

  23. ebors says:

    Hi there i have tried to run this on the new version of ionic, and i put the initialization part on the /src/app/app.component.ts, after new sidemenu project, installed firebase with npm, and added there:

    @Component({
    templateUrl: ‘app.html’
    })
    export class MyApp {
    @ViewChild(Nav) nav: Nav;

    rootPage: any = Page1;

    pages: Array<{title: string, component: any}>;

    constructor(public platform: Platform) {
    var config = {
    apiKey: “AIzaSyClQZVm3tOsPtDywLHo9kGnszeyYugPDp4”,
    authDomain: “footballproject-e6e5b.firebaseapp.com”,
    databaseURL: “https://footballproject-e6e5b.firebaseio.com”,
    storageBucket: “footballproject-e6e5b.appspot.com”,
    messagingSenderId: “499133165869”
    };

    // this.initializeApp();
    firebase.initializeApp(config);

    but i hve got an error : rollup: Export ‘initializeApp’ is not defined by … component.ts … shoudl i continue the steps with d.ts as well?
    Thanx

    • Colin says:

      Yeah, it sounds like there’s a type error with the method that you’re calling. If you haven’t yet included the typings, or if you’re not importing firebase in that component’s file, that would probably have something to do with it. So I would say go ahead with the steps for the d.ts file and see how that works out.

Leave a Reply