Using Cloud Firestore in Ionic 3 With AngularFire

Monday, 9 October 2017

Firebase has just announced  Firestore which is NOSQL document-based database. As compare to Firebase real time database in Firestore you can use simple and compound queries to fetch and retrieve the data.
In this tutorial we will learn how to integrate Firestore with Ionic 3. 
Follow these following easy steps.

Step-1

First you need to create a new project using Ionic CLI. If you don't know how to create new project using Ionic CLI please read this article  Set Up Development Environment for Ionic Framwork . Just open your terminal or command prompt. Create a project by using this command.


ionic start myApp tabs

If you have already created project then you can skip this step.


Step-2

Go to root directory of your project now you need to install Firebase package. Install angularfire 2 in your ionic project by using npm.


npm install angularfire2 firebase promise-polyfill --save



Step- 3

Now configure firebase in your application goto your firebase console and copy your API keys.
and  add both the AngularFireModule and AngularFirestoreModule to your app module.
See in the code sample.



import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';

  export const firebaseConfig = {
     apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
     authDomain: "your-app.firebaseapp.com",
     databaseURL: "https://your-app.firebaseio.com",
     storageBucket: "your-app.appspot.com",
     messagingSenderId: "01234567891"
 };

@NgModule({
  declarations: [
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFirestoreModule.enablePersistence(),

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    HomePage
  ],
  providers: [
    StatusBar,AndroidPermissions,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Here we call the enablePersistence method on the AngularFirestoreModule to automatically enable local caching which will allow the app to stay available while offline.

Step-4

Your firebase firestore configuration is now ready for use. Just import and use firestore on any page.


import { AngularFirestore } from 'angularfire2/firestore';
@Component({
  selector: 'page-hone',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,public afs: AngularFirestore) {

  }

}

Create database reference and use AngularFirestore.

To Add documents to a collection

You can use the add() method to add a new document to a collection with a generated id.
Sample code


import { AngularFirestore } from 'angularfire2/firestore';
@Component({
  selector: 'page-hone',
  templateUrl: 'home.html'
})
export class HomePage {
constructor(public afs: AngularFirestore) {

const carsCollection = afs.collection<Item>('mycars');
   carsCollection.add({
    name: 'Abc',
    model: 'xyz',
    price: 10000
    }).then((added)=>{
console.log(added.id);
}).catch((e)=>{
console.log("Error",e);
})
  }

}

Retrieving collection data

There are multiple way to Retriving collection data from firestore.
If you just need the object data use valueChanges() method. With valueChanges() method  no document metadata is attached which makes it simple to render to a view.
snapshotChanges() method  returns an Observable of data as a DocumentChangeAction.
Sample code

import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'page-hone',
  templateUrl: 'home.html'
})
export class HomePage {
private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(public navCtrl: NavController,public afs: AngularFirestore) {
 this.itemDoc = afs.doc<Item>('mycars');
    this.item = this.itemDoc.valueChanges();
  }

}

On Your HTML Page


     <div>
      {{ (item | async)?.name }}
    </div>

For  setting, updating, and deleting document data use set(), update(), delete() methods.
Reference is taken from https://github.com/angular/angularfire2
If you face any problem you can comment below. Thank You


3 comments

  1. So how do you get data from this point onto the screen? Could you add more detail ?

    ReplyDelete
    Replies
    1. Additional details is added.
      Thank You

      Delete
    2. Quick query w.r.t. this example, especially the code below i.e.
      ---
      export class HomePage {
      private itemDoc: AngularFirestoreDocument;
      item: Observable;
      constructor(public navCtrl: NavController,public afs: AngularFirestore) {
      this.itemDoc = afs.doc('mycars');
      this.item = this.itemDoc.valueChanges();
      }
      ---

      What is the structure definition of the model on the Firebase Database that has to match this code ?

      A screenshot of that would help.

      Delete

Related Posts Plugin for WordPress, Blogger...
Related Posts Plugin for WordPress, Blogger...
 

Most Reading

Labels