Firebase

Building a CRUD Ionic 2 Application with Firebase & AngularFire

·

Firebase is one of the most powerful and popular Database as a Service (DBaaS) solutions available today. It provides a document based NoSQL database, with real-time capability, and it is hosted as a service by Firebase so you don’t need to worry about scaling your own servers. Support for Firebase in Ionic 2 has been growing recently, and in this post, we have the community’s resident Firebase + Ionic 2 expert, Jorge Vergara, walking you through how to build your own Firebase application in Ionic 2. Make sure not to miss the bonuses he is offering at the end of this post.

Here’s Jorge…

Do you want to develop an app using Firebase but whenever you start you end up looking at a blank screen without knowing what to do?

I was in that same position a few months ago, I couldn’t understand the docs (or in AngularFire’s case there weren’t any) and I was just staring at the blinking cursor, trying to figure out my first move.

Today I’m going to get you started, I’m going to show you how to set up an Ionic 2 and AngularFire2 project.

As soon as everything is set, we’ll dive into one of the most common things you’ll need to do, CRUD.

You’ll be creating songs and pushing them to a list, you’ll show them in the app’s HomePage, you’ll know how to edit their titles or even just delete them.

So go get your poison (mine is coffee) and get ready to code πŸ™‚

We’re going to break the process in 2 parts, the first will be to handle all configuration and then we’ll create the functionality.

Configure your app

Is your development environment up to date?

Before writing any code, we’re going to make sure everything is up-to-date (about half of the problems people message me about are solved with just installing the updated versions of everything)

The first thing you’ll do is to make sure you have node.js installed, get V6.

The second thing you’ll do is make sure you have Ionic, Cordova and Typescript installed, you’ll do that by opening your terminal and typing:

$ npm install -g ionic cordova typescript

Depending on your operating system (mostly if you run on Linux or Mac) you might have to add sudo before the npm install.... command.

Notice that we’re using ionic this is to access the most up-to-date version of their build tools, we get lighting fast builds + error reporting with colors in our terminal πŸ™‚

Create the App

Now that you made sure everything is installed and up to date, you’ll create a new Ionic 2 app.

Open your terminal, navigate to the folder you want to create it and type:

$ ionic start af2-lists blank --v2

That means:

  • ionic start creates the app.
  • af2-lists is the name we gave it.
  • blank tells the Ionic CLI you want to start with the blank template.
  • --v2 tells the Ionic CLI you want to create an Ionic 2 project instead of an Ionic 1 project.

From now on, whenever you are going to type something in the terminal it’s going to be in this folder.

The npm packages that come with the project

When you use the Ionic CLI to create a new project, it’s going to do a lot of things for you, one of those things is making sure your project has the necessary npm packages/modules it needs.

Your package.json file should look like this:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic/storage": "1.1.7",
    "ionic-angular": "2.0.0-rc.4",
    "ionic-native": "2.2.11",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.47",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-statusbar",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "af2-lists: An Ionic project"
}

Install the packages you’ll need

After you make sure that the Ionic CLI started/installed everything correctly, it’s time to install the packages we’ll need for this app.

First, we’ll need to update @ionic/app-scripts to use the latest version, since that’s the one with Webpack support, meaning it works with Firebase out of the box, you won’t have to create custom builds.

$ npm install @ionic/[email protected] --save-dev

That will tell Ionic to use the latest version of the module and you’ll get webpack support.

Now it’s time to install AngularFire2, open your terminal (you should already be in the project folder) and install it:

$ npm install angularfire2 --save

Import and Initialize

Now you can initialize firebase by going to src/app/app.module.ts and importing everything you need from Firebase:

You can open your app.module.ts and import everything we’ll be using, this is the only time you’ll see this file πŸ™‚

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

// Import the AF2 Module
import { AngularFireModule } from 'angularfire2';

// AF2 Settings
export const firebaseConfig = {
  apiKey: "AIzaSyDnAX0CQbbsMYuOTJ66ox_F0GwzPM4XPXY",
  authDomain: "angularfire2-list-example.firebaseapp.com",
  databaseURL: "https://angularfire2-list-example.firebaseio.com",
  storageBucket: "",
  messagingSenderId: "609067141823"
};

And then add the initialize to @NgModule:

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

In the end the file should look like this:

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

// Import the AF2 Module
import { AngularFireModule } from 'angularfire2';

// AF2 Settings
export const firebaseConfig = {
  apiKey: "AIzaSyDnAX0CQbbsMYuOTJ66ox_F0GwzPM4XPXY",
  authDomain: "angularfire2-list-example.firebaseapp.com",
  databaseURL: "https://angularfire2-list-example.firebaseio.com",
  storageBucket: "",
  messagingSenderId: "609067141823"
};

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

We are using:

// AF2 Settings
export const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  storageBucket: "",
  messagingSenderId: ""
};

To store our config object. We then pass it to:

AngularFireModule.initializeApp(firebaseConfig)

Right there your app should be able to run without any errors when you do ionic serve

You can find your firebaseConfig data in the Firebase’s Console.

You just go to the console, click on your app (or create a new one) and there it’s going to give you a few choices.

You’ll pick Add Firebase to your webapp because remember we are going to use a mix of AF2 with the JS SDK.

Firebase Web Console

Start adding functionality

Now that we have everything ready we can start coding (a tip for you here, save the project right now in a git repository and then clone it every time you’re starting a new AngularFire2 project, it will make your life easier)

Handling the view

The first thing we’ll do is to build our view (the HTML template) so that we don’t have to edit this file again in the future and you’ll be able to focus on coding.

The file needs 3 things:

  • A button to create a new song.
  • To show the list of songs stored in Firebase.
  • A button to edit/delete songs.

First, we’ll add the button to create new songs, we’ll create a nav-bar button only showing the + sign as an icon.

For this, open home.html and inside the <ion-navbar> just after the <ion-title> you’ll add:

<ion-buttons end>
  <button ion-button icon-only (click)="addSong()">
    <ion-icon name="add"></ion-icon>
  </button>
</ion-buttons>

Let’s review that snippet:

  • It’s adding the button to the end (that means it’ll add it to the right side of the screen).
  • It’s using the icon called add which is just a plus sign.
  • When clicked is calling the addSong() method (which we’ll create in the home.ts file later).

Now we’ll show the list of songs in the view, for that add this inside the <ion-content> tag:

<ion-list>
  <ion-item *ngFor="let song of songs | async">
    {{song.title}}
  </ion-item>
</ion-list>

That snippet will create a list and populated with all the songs it finds in the songs array, we’ll create it next.

It’s also using the async pipe, because AngularFire2 returns Observables, which means it’s going to be retrieving the list items and sending them to the view as soon as they become available.

And now we just need to add a way to edit/remove the songs in the list, for that, we’ll add a click handler to the <ion-item> tag:

<ion-item *ngFor="let song of songs | async" (click)="showOptions(song.$key, song.title)">

That click handler is calling our function showOptions() and passing the song’s title and id (this is going to display an action sheet).

It’s coding time

Now we’re going to move to home.ts and we’ll start building all the functionality for the view we just created.

Remember we need to accomplish 4 things here:

  • List all the songs in the view.
  • Create new songs.
  • Update a song’s title.
  • Delete a song from our list.

First, we’ll create the song list that we’ll pass to the view, for that we’ll need to do a few things:

Import AngularFire2 and the list observable:

import {AngularFire, FirebaseListObservable} from 'angularfire2';

Then create the songs variable right before the constructor:

songs: FirebaseListObservable<any>;

Now we’ll inject AngularFire2 in our constructor and initialize the songs variable.

constructor(public navCtrl: NavController, af: AngularFire) {
  this.songs = af.database.list('/songs');
}

We’re creating a database reference that listens to the songs node inside our Firebase database. It’s already synced to our app, so if you open your Firebase console and create a record there it will show up in your HomePage.

Songs node

It’s also using Firebase real-time bindings, so you won’t have to refresh the view to notice changes to any of the songs.

Now it’s time for us to test that, for that, we’ll build a function that will allow us to create new songs and push them to the list.

There are times where you need a separate page/view with the creation form, but since it was just a song title we’re going to create a prompt so the user can just add the name without moving to a different page.

First, we’ll import the controller for alert prompts.

import { NavController, AlertController } from 'ionic-angular';

Now, we need to inject it to the constructor:

constructor(public navCtrl: NavController, public alertCtrl: AlertController, 
  af: AngularFire) {...}

We can now create the function, remember how we named it in the home.html file?

addSong(){
  let prompt = this.alertCtrl.create({
    title: 'Song Name',
    message: "Enter a name for this new song you're so keen on adding",
    inputs: [
      {
        name: 'title',
        placeholder: 'Title'
      },
    ],
    buttons: [
      {
        text: 'Cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'Save',
        handler: data => {
          this.songs.push({
            title: data.title
          });
        }
      }
    ]
  });
  prompt.present();
}

I hope that code isn’t weird or anything, it’s just the basic alert code, pay attention to this bit:

{
  text: 'Save',
  handler: data => {
    this.songs.push({
      title: data.title
    });
  }
}

That right there is taking the song title we just add and pushing it to the database.

Songs node

Firebase we’ll create the object for you, and it will assign it a unique ID without you doing anything else.

You can now create objects and push them to Firebase’s real-time database, how cool is that!?

We now need a way to delete/update our songs, for that we’ll create an action sheet, basically when you click on a song we want it to display 3 options, remove, edit and Cancel.

To create an action sheet you’ll need to first import the controller, go ahead and do that:

import { 
  NavController, 
  AlertController, 
  ActionSheetController } from 'ionic-angular';

Now, just like with the AlertController we need to inject it in the constructor:

constructor(public navCtrl: NavController, public alertCtrl: AlertController, 
  af: AngularFire, public actionSheetCtrl: ActionSheetController) {...}

Now we want to bind it to the showOptions() function we created on the home.html file:

showOptions(songId, songTitle) {
  let actionSheet = this.actionSheetCtrl.create({
    title: 'What do you want to do?',
    buttons: [
      {
        text: 'Delete Song',
        role: 'destructive',
        handler: () => {
          this.removeSong(songId);
        }
      },{
        text: 'Update title',
        handler: () => {
          this.updateSong(songId, songTitle);
        }
      },{
        text: 'Cancel',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }
    ]
  });
  actionSheet.present();
}

The function is receiving the song’s id and title as parameters, and then it’s going to use them to pass them to the delete and the update functions.

The first part is passing the song’s ID to the delete function:

{
  text: 'Delete Song',
  role: 'destructive',
  handler: () => {
    this.removeSong(songId);
  }
}

Go ahead and create that removeSong() function:

removeSong(songId: string){
  this.songs.remove(songId);
}

That simple code .remove() will go to the list, find the correct song and then return a promise, so you can use a .then() if you want to perform another action after deleting.

The next part of the action sheet code:

{
  text: 'Update title',
  handler: () => {
    this.updateSong(songId, songTitle);
  }
}

Will take the song’s ID and title and pass it to an updateSong() function, we’ll create it right now:

updateSong(songId, songTitle){
  let prompt = this.alertCtrl.create({
    title: 'Song Name',
    message: "Update the name for this song",
    inputs: [
      {
        name: 'title',
        placeholder: 'Title',
        value: songTitle
      },
    ],
    buttons: [
      {
        text: 'Cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'Save',
        handler: data => {
          this.songs.update(songId, {
            title: data.title
          });
        }
      }
    ]
  });
  prompt.present();
}

Notice something similar about it?

It’s basically the same as the addSong() function with 2 small differences:

  • On the input object, we’re adding a value property and passing it the current name:
inputs: [
  {
    name: 'title',
    placeholder: 'Title',
    value: songTitle
  },
],

And in the handler object we’re passing the new song’s name with its ID to an .update() function:

{
  text: 'Save',
  handler: data => {
    this.songs.update(songId, {
      title: data.title
    });
  }
}

That function will find the correct song and update its name.

The coolest thing about AngularFire2 is that if you’ve been paying attention and building the app alongside with me, you’ve noticed your songs updating in real-time, without you needing to do anything else πŸ™‚

Conclusion

By now you should have a fully working Ionic 2 + AngularFire2 app, we:

  • Made sure everything was up-to-date.
  • Created the app and set up all the config.
  • Created the HTML template.
  • Added the CRUD functions to our TypeScript file.

The next thing you should do is to get familiar with Firebase as a whole, to build more complex apps.

I created a little bonus to help you achieve just that πŸ™‚

You’ll get:

  • The source code for this app, so you can just do npm install and get up and running.
  • A self paced 7-lesson Ionic 2 + Firebase 3 crash course, where you’ll work at your own pace and only get the next lesson after you’ve finished the one you’re working on.
  • 20% discount for my book Build your first Firebase powered Ionic 2 app.

All you need to do is click here to claim your bonuses

What to watch next...

  • maddi hanna

    I so love javebratt explanation! thank you for successful cooperation!!!
    where can i find the provider part? how to saveupdate with firebase?

    p.s
    I love also yours tutorials,josh!

  • Ted

    Just easing myself into Firebase so just imported my JSON data into Firebase console and using it with http:get for the moment in my app for now. So this question is slightly off track, but perhaps will come in useful down the line when filtering data queries in Firebase.

    I can access via REST API with https://s3.postimg.org/4794i57ab/firebaseapisongs.jpg

    If you had more songs in there and perhaps an artist field, how could I pull just the artist info for all songs by Ali G via REST API?

    example attempt: https://angularfire2-list-example.firebaseio.com/songs/*/artist:Ali-G.json

    • You’d need to structure the data differently, then pull the node you need.

      For example, in firebase you can query lists, meaning you can query the list asking if the artist in the artists filed matches your query.

  • Omotayo Iginla

    i was wondering, having the same question with maddi hanna, or was wondering if angular fire handled that itself

    • AngularFire2 handles all of it, just needs to .push or .update πŸ˜›

  • Elton

    Do I need to change from the default Firebase Rules (auth required for read and write) to allow anonymous access in order to get this tutorial to work? I am getting permission denied errors…

    • Yeah, if you’re going to have un-authenticated users read the data you should state that on the security rules.

      • Marcos Eduardo

        how i do this, i dont know the steps :{

      • Take a look at this https://javebratt.com/firebase-security-rules-ionic-apps/ or search in youtube “Firebase database for SQL with David East”

      • Inspired

        Hey Marcos,

        Log into your Firebase Console, go to your Database and select the “Rules” tab.

        Then change your rules to the following for un-authenticated use:

        {
        “rules”: {
        “.read”: true,
        “.write”: true
        }
        }

        Hope that helps.

    • Marcos Eduardo

      man same error here, pls help

    • Marcos Eduardo
      • Dev Salou

        you can simply login as anonymous, if you allowed anonymous to read/write your DB. Not realistic in prodction environment, but enough just for a test. _To do so, just add this in your code (home.ts):

        constructor(public navCtrl: NavController, public alertCtrl: AlertController, fire: AngularFire) {
        fire.auth.login(this.getAuth())
        this.bottles = fire.database.list(‘/bottles’);
        }

        private getAuth(): AuthConfiguration {
        let me: AuthConfiguration = {
        method: AuthMethods.Anonymous, provider: AuthProviders.Anonymous
        };

        return me;
        }

        and go to your firebase console, “authentication” / “connection mode” then allow anonymous login.

        It works for me.

  • Stanley_Krute

    When I click Add Firebase to web app …, I get a bunch of code to copy. Where do I place that code ?

    • It gives you the details that you add to app.module.ts

      You add it above NgModule() in app.module.ts in the following example from Jorge:

      // AF2 Settings
      export const firebaseConfig = {
      apiKey: “”,
      authDomain: “”,
      databaseURL: “”,
      storageBucket: “”,
      messagingSenderId: “”
      };

      Just replace the code in firebaseConfig with the configuration details you get from Firebase.

  • I’m on RC3 and getting the following error after setting up Firebase in app.module.ts and running “ionic serve”

    build dev failed: Cannot read property ‘indexOf’ of undefined

    The project is brand new and the only changes are to add firebase and declare it in app.module.ts

    Any ideas?

    • Is this still going on with yesterday’s update of the book? If so, shoot me an email and I’ll help you debug it

      • Heya,

        I havent had a chance to check and verify yet. I posted this round about the same time that I messaged you.

      • Alright, let me know after you try it

      • Daniel Marc Ehrhardt

        Hi
        i have the same Problem.

        Thanks

  • Steve Melnikoff

    Hi, simply beautiful … thanks for crafting a painless introduction to ionic2/firebase3 (much easier than going to the dentist). Small coding note, line #10 of updateSong(), has an extra comma following the inputs array first/only element.

  • Pouloum

    Thank you @javebratt:disqus for this ionic2/firebase introduction. Everything is clear for me except two things:

    – Why do you need to install @types/request and firebase npm modules ? Indeed I just install angularfire2 module and everything works like charms. As angularfire2 and request and firebase are dependencies of angularfire, webpack resolve the dependencies injection tree.

    My bonus question is why Angular/Ionic ? need entryComponents arry in the app declaration module. What is this purpose ?

    Have a good day πŸ˜‰

  • Marcos Eduardo

    I searched a lot on the internet but until now I can not run my application on my windows 10 mobile device. heeelp

  • Adir Zoari

    can i use the data of ” this.songs = af.database.list(‘/songs’)” into the ts file? I mean to iterate with loop on all the values into ts file and do something with them?

  • anivaishu

    Hi all,

    I used angular fire 2 with ionic 2
    How to Push child with collection
    I need Following Output Using angular fire 2

    {
    ASSIGN_TO: “2”
    COMMENTS:{
    dfdsfdf:{
    COMP_STATUS: “OnProcess”,
    DATE: “2016-12-16 09:57:03”
    },
    fgfd:{
    COMP_STATUS: “OnProcess”,
    DATE: “2016-12-16 09:57:03”
    }
    }
    }
    Kindly Advice me,
    Thanks & Regards

  • I’m getting the following error…

    Runtime Error

    Error in ./MyApp class MyApp – caused by: No provider for AngularFire!

    Any advice on how to resolve?

    Thanks

    • Siraa pora

      just run
      $ npm install firebase –save

  • nuruddin

    hi thanks for this Article, i would to ask how i can allow still working in offline mode ?

  • George Huang

    In your “$ npm install angularfire2 –save” you might want to change it to “$ npm install angularfire2 firebase –save”. Otherwise we will get UNMET Peer Dependency error.: requires a peer of [email protected]^3.xx …
    With npm 3 and up, the automatic install of peer dependencies was explicitly removed.

    • Wade Bekker

      Thank you very much George! I got a ton of error messages in the console and your advise cleared it all! Appreciate it.

    • Inspired

      Wow!, Thanks George.

      Your comment should be integrated into the tutorial. It definitely saved me some headache. Thank you!

  • Hector Llorens

    Hi, how would you add a ionic2 search element to filter out the songs by the title?

  • Snaketech

    hello

    i am having a problem a local json data about assign to variable .Δ° can make a local conneciton with subscribe but it cant be assign to a variable … i dont really understand whats the problem is .I read loads of documents to solve this problem but i didnot please help me

  • Mritunjay Singh Khichi

    how to create log out function and button please check link below
    https://github.com/javebratt/ionic-angularfire2-email-auth/tree/master/src

  • Peter

    Hi

    Works fine with ionic serve -l (browser).

    Has anyone try to deploy to android mobile?

    I have faced an issue firebase not retrieving the records in android mobile?

    • Abu Nj

      push() not working, listing ok

  • Arthur Ebing

    Hi Josh and Jorge,

    Great tutorial, thanks guys!

    I know I need to set the permissions on the firebase console (which works perfectly), but is there a way of handling a “client doesn’t have permission” error more elegantly instead of just crashing out? So basically when I do “this.songs = af.database.list(‘/songs’);” is there a way of checking if the user has access before and wrapping it in an IF or is there a .catch I can use?

    Thanks guys!
    Arthur

  • Abhishek Saxena

    error_handler.js:53Error: Uncaught (in promise): Error: permission_denied at /songs: Client doesn’t have permission to access the desired data.

    Error: permission_denied at /songs: Client doesn’t have permission to access the desired data.

    please help me out

    • Inspired

      Hey Abhishek,

      It looks like you need to allow un-authenticated users to read and write to your Firebase DB (or authenticate your ionic app’s user).

      You can learn about it here: https://firebase.google.com/docs/database/security/quickstart

      Basically go to your Firebase Console and set your Database Rules to:

      {
      “rules”: {
      “.read”: true,
      “.write”: true
      }
      }

      This will allow anyone to read and write to your DB. Of course you could enable authentication, but taking auth off for the sake of this tutorial should get you up and running quickly.

  • Jeff Leigh

    Is your “bonus” source code meant to be a “starter” repo or working code for this app? I just signed up for and cloned it and it doesn’t even have angularfire in package.json so I’m not sure how you can “just do npm install and get up and running.” with it.

  • Inspired

    Somehow, your article is thorough, but not verbose and demonstrated the awesome productivity power of Ionic with Firebase.

    Great article, Thank you!

  • Very good

  • asep furkon efendi

    Thank you mr George!….
    very helpful for me…

  • Pingback: Google()

  • Pingback: waterproof vibrator()

  • Pingback: male vacuum pump()

  • Pingback: Carlin Ross()

  • Pingback: sex comedy()

  • Pingback: ashbourne()

  • Pingback: vape shop()

  • Ok so, Everything worked great until I took the firebase initialize out of the index.html and placed it like you have above. Now all I get is:
    “No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app).”
    I’ve been going fine with it in the index.html but for obvious reasons, I want it where you have it.
    Can you help?

    Here is my code from app.module.ts:
    import { AngularFireModule} from ‘angularfire2’;

    export const firebaseConfig = {
    apiKey: “***”,
    authDomain: “***”,
    databaseURL: “***”,
    storageBucket: “***”,
    messagingSenderId: “***”
    };
    firebase.initializeApp(firebaseConfig);

    imports: [
    IonicModule.forRoot(MyApp),
    IonicModule.forRoot(MyApp,{tabsPlacement: ‘top’}),
    AngularFireModule.initializeApp(firebaseConfig),
    FormsModule

    Thanks!!

    • Jeff Leigh

      You don’t need to call this:

      firebase.initializeApp(firebaseConfig);

      under your:

      export const firebaseConfig = {

      It should just be in the imports, perhaps the error is coming from the first one.

      • Removing it doesn’t seem to work either. Again, If I import * as firebase from ‘firebase’; at the top, that doesn’t help either. I swear I’ve tried every combination I can think of. Thanks for helping I’ll post the solution if I find one.

  • Pingback: natural remedies for pink eye()

  • Pingback: Download CPR Certification Dumps()

  • Pingback: Search Engine()

  • Pingback: Logitech keyboard compared()

  • Pingback: microcamere spion()

  • Pingback: Wireless headset systems()

  • Pingback: 70-243 Certification Exam Questions and Answers()

  • Pingback: backgammon game()

  • Pingback: mitsubishi fuso service georgia()

  • Pingback: pc games free download for windows 8()

  • Pingback: facebook likes panel()

  • Shane Lester

    Hi- is there any way to switch the database used within the app?

  • Pingback: rotating vibrator()

  • Pingback: rabbit vibe()

  • Pingback: feather tickler()

  • Pingback: rabbit vibrator review()

  • Pingback: adam and eve coupon code()

  • Mahim Parsai

    hello, thanks for the tutorial. Is there any way to use validators in the input fields ?

    • You can create validators manually like:
      if(username != “” && username.length >= 3){
      pass;
      }else {
      fail;
      }

      If you’re using firebase, you can use the .validator method to validate the data coming into the DB is correct. These should be done in tandem.
      See here. This video explains it really well. https://www.youtube.com/watch?v=PUBnlbjZFAI

      • Mahim Parsai

        thanks for the answer, I used the ionic modal instead with form. Also is there any way to dynamically add an input field ?

      • Based on your last response, I’m guessing you want to keep this all Ionic. If that’s the case, i’m not sure what the correct method would be. There are other ways to do it with JS though.

  • Connor Dodge

    Not working for me. Following the tutorial as written, I get the following error after running ionic serve the first time.

    Runtime Error
    No provider for ApplicationInitStatus!

    Looking at the package.json file it seems like the download comes with ionic3 and angular4

    • Paulo Ruca

      Show me your code
      I have the same error too and i resolve

    • I have this issue too.

    • Marty

      Check the spelling, and particularly lower/uppercase, for accuracy in all of your import statements (in all of your .ts files). I didn’t have this exact error, but a different “No provider” error, and it was because of using an uppercase char instead of a lowercase in one of my import “from”s.

    • Anuptha

      I’m getting the same error. I hope when you tried to install ionic it asked to remove –v1 or –v2 flag since these flgs have been removed. try checking ionic -v. I can see it is ionic 3 not ionic 3. I couldn’t figure out the problem though. Thank you

      • Anuptha

        To explicitly install ionic 2 try this command npm install -g [email protected] Let me know if u still face the same problem.

  • Hopefulbucket

    I’m trying to change the code to work best for me but when I tried to change the update method I get Firebase.update failed: First argument contains undefined in property it didn’t throw this when it was setup with title. The other parts I modified for adding work fine with all different values and types. https://uploads.disquscdn.com/images/2d94debc65cd7bdf5fec73486b44f98d9728e4c829aaacc637a61361b490ee70.png

  • Martin_H_Andersen

    Thanks a trillion saved me a lot of time.
    Can you point me to an article on how to use firebase authentication?

  • Juan Zapata

    Outstanding, I was watching some ionic1 tutorials and it was a headache comparing with this extremelly simple sample with Angular2+TS

    Thank ou so much!

  • youp_han

    Thanx.. Great Tutorial. It got me going. Thanx
    For some version differences, I had to change to “import { AngularFireDatabase, FirebaseListObservable } from ‘angularfire2/database’;” in home.ts, and added “import { AngularFireDatabaseModule } from ‘angularfire2/database’; ” and “AngularFireModule.initializeApp(firebaseConfig), AngularFireDatabaseModule”in app.module.ts. It worked great!!

    • Jay

      This solved a lot of my issues, but in my constructor(public navCtrl: NavController, public alertCtrl: AlertController,
      af: AngularFire, public actionSheetCtrl: ActionSheetController)

      The af: AngularFire says ‘cannot find name ‘AngularFire’

      Any ideas?

      • youp_han

        I think you’re talking about the “home.ts” file. The following is what I’ve done.
        I’ve added:

        ” import { AngularFireDatabase, FirebaseListObservable } from ‘angularfire2/database’; ”

        and this is the constructor:

        ” constructor(public navCtrl: NavController, public alertCtrl: AlertController, aDB: AngularFireDatabase,
        public actionSheetCtrl: ActionSheetController) {
        this.books = aDB.list(‘/Books’); } ”

        I hope it works out for you

  • OfficialCH

    Nice tutorial, thank you. Do you know how I can display my songs in the html with filter (by the artist, by year) with button for example. Thank you !

  • Dimitris Greasidis

    Hello there and thanks for the tutorial. For a lot of reasons this tutorial did not work for me as expected, so i created a new project and published it here: https://github.com/Temeteron/ionic2-firebase-starter-kit . Anyone who has any problem with this tutorial could possibly find a solution on this project.

    • Jeff Leigh

      You might want to change your description on github – “angularjs” refers specifically to version 1.x now, you should just say Angular 4

      • Dimitris Greasidis

        yeah, you are probably right, thanks a lot

    • Jay

      Hey thanks a ton bro. I’ve been working on crud for over a week now and this is the first github that got me going first try. You’re officially my hero!

  • Poly Former

    Thanks for the tutorial.
    It has been updated but looking at `https://github.com/javebratt/angularfire2-crud-lists` there are many discrepancies in the files, nomenclature and structure.
    A lot of people visit your site to gain something useful and most of them end up shooting themselves in the foot.
    If you’re going to provide a learning tutorial, either do it properly and let eager readers actually learn something or point them to your other sites where they can purchase the resources.
    Your value lies in community benefit and not how much dosh you can fleece from these folks.
    I’ve purchased your resources and I know what you’re capable of and it so much more than this (and many like it) tutorial.

  • Johan Uys

    Is it possible to use angularfire with iconic 3?

  • ammar

    iam importing this “AngularFire2” module and getting this error
    [ts] Module ‘”c:/path”‘ has no exported member ‘angularfire’

    • Ripulryu

      Angularfire2 no longer exists, it is now : reference : https://github.com/angular/angularfire2/issues/854

      import {FirebaseListObservable} from ‘angularfire2/database’;

      • Sean Letendre

        Ok, import {FirebaseListObservable} from ‘angularfire2/database’; works, but from where do I import {AngularFire}? Or should it be import {AngularFireModule} from ‘angularfire2’; ?

      • vipul korgaonkar

        `Were you able to use {AngularFireModule} successfully? I did try importing that but I am then unable to access af.database

      • VITHIKA GUPTA

        I am facing the same issue…did you resolved it…

      • vipul korgaonkar

        Yup.. Try importing { AngularFireDatabase } from ‘angularfire2/database’..

      • VITHIKA GUPTA

        thanks ..error resolved

      • Sean Letendre

        Oh, never mind. I cannot import it at all. But should I import FirebaseApp or AngularFireDatabase instead?

  • akshat

    Hello Sir
    In one of your latest video about security says that app’s whole code is viewable by any user and in almost all the tutorials about integrating firebase in ionic 2 app, it says to init angularfire2 modules in our app.module.ts so for that one also need to pass its firebase config which gives access of my firebase config to the user. So is developing app this way a secure way? What can be other option for me to consider for using firebase in my ionic app with security?

  • powderriverfarrier

    Lots of “doesn’t exist” errors when trying to compile the code with the latest modules so it looks like this broken tutorial is out of date.

  • Sean Letendre

    What if my package.json does not include the entry “cordova-plugins”. My app is of type “ionic-angular not ionic 2 because the –v2 tag was deprecated, does that matter?

  • Burhanuddin Lokhandwala

    there is a version update of angularfire2…. make the changes give in the below link
    https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md

  • Spam Bot

    Hi, with Firebase 4.0 somethings changed in the Firebase Module:
    So at home.ts you have to

    import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from ‘angularfire2/database

    in constructor use af: AngularFireDatabase.

    to list songs use

    this.songs = af.list(‘/songs’);

    in app.module.ts add:

    import {AngulaFireDatabaseModule} from ‘angularfire2/database’

    after AngularFireModule.initializeApp(firebaseConfig); add
    AngularFireDatabaseModule

    Have fun πŸ™‚

  • Satish Nani

    i am getting error with import statement error = ” (import {AngularFire} from ‘angularfire2’)”

    • Bongani Dlamini

      Update it to this line import {AngularFireModule } from ‘angularfire2’;

  • Sabari nathan
    • Sabari nathan

      I follow the above tutorial?? does any one face this issue?

    • Bongani Dlamini

      Try changing your firebase database permissions/rules to

      {
      “rules”: {
      “.read”: true,
      “.write”: true
      }
      }

      • Sabari nathan

        thanks..

  • Kantaris

    When I click on a song, how can I get it to push the information over to another page and display the info for that specific song on the details page?

    • HectorM

      You need to use the navController and pass the song object:
      this.navCtrl.push(songDetailPage, {
      song: specificSong // the “song” object will be available in the songDetailPage
      });