Skip to content

Instantly share code, notes, and snippets.

@debojyoti
Created December 4, 2018 19:30
Show Gist options
  • Save debojyoti/dcc56908eec46ee3b9bb72664a758c47 to your computer and use it in GitHub Desktop.
Save debojyoti/dcc56908eec46ee3b9bb72664a758c47 to your computer and use it in GitHub Desktop.

Firestore setup and basic opertaions in Angular 7

Step-1: Prepare firebase firestore

1.1) Create a new project from firebase console

1.2) Go to newly created project page and create a database

1.3) Select "Start in test mode"

1.4) Create a new collection with a new document in it

Step-2: Setup firebase in angular-project

2.1) Install the Firebase module

npm install @angular/fire firebase --save

2.2) Update rxjs and add rxjs-compat

npm i rxjs@latest rxjs-compat --save

2.3) Add firebase configuration

2.3.1) Goto firebase site and get web configuration (Overview->web) 2.3.2) Add the config in app.module.ts

const settings = {timestampsInSnapshots: true};
const config = {
  apiKey: 'YOUR_APIKEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  databaseURL: 'YOUR_DATABASE_URL',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
};

2.4) Register the Firebase module

...
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore } from '@angular/fire/firestore';
...

const settings = {timestampsInSnapshots: true};
const config = {
  apiKey: 'YOUR_APIKEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  databaseURL: 'YOUR_DATABASE_URL',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
};

...
@NgModule({
    ...
    imports: [
        ...
        AngularFireModule.initializeApp(config, settings)
    ],
    ...
    providers: [
        ...
        AngularFirestore
      ]
})
export class AppModule { }

2.5) Use firestore db in a component

import { Component } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

...
export class AppComponent {
    ...
    constructor(
        public db: AngularFirestore
    ) { }
}

Step-3: Read operation

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

import { AngularFirestore } from 'angularfire2/firestore';

@Component({
    selector: 'app-root',
    template: `
        <ul>
            <li *ngFor="let item of items | async">
                <pre>{{ item | json }}</pre>
            </li>
        </ul>
    `
})
export class AppComponent {
    public items: Observable<any[]>;

    constructor(db: AngularFirestore) {
        this.items = db.collection('/items').valueChanges();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment