Firestore with AngularFire

September 9, 2018
cgrant

Firestore with AngularFire

1. Firestore with AngularFire

Install

npm install firebase angularfire2 --save

Configure

Add keys & config to environments.ts


export const environment = {
  production: false,
  firebase: {
    apiKey: " ",
    authDomain: " ",
    databaseURL: " ",
    projectId: " ",
    storageBucket: " ",
    messagingSenderId: " "
  }
};

Add imports to app.module.ts


import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';
...
@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],

Add the FireBase modules you’re going to use


...


@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule, // imports firebase/firestore, only needed for database features
  ],

Use Firestore

On your component Import AngularFirestore and inject a DB in the constructor for use


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

export class MyApp {
  items: Observable<any[]>;
  constructor(db: AngularFirestore) {
    this.items = db.collection('items').valueChanges();
  }
}

Firestore as an Angular Service

Create a service, attach to the collection, return the observable collection


import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';

@Injectable({
  providedIn: 'root'
})
export class ChatService {

  constructor(private db : AngularFirestore) {}

  getChatCollection(){
    return this.db.collection('chat').valueChanges();
  }
}

Consume your service

From your component, import the service you just created and set your local variables onInit. We’re converting from observable to local value in the subscribe section.


import { Component, OnInit } from '@angular/core';
import { ChatService } from '../chat.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit {

  thread$ : Object;
  constructor(private data: ChatService) {}

  ngOnInit() {
    this.data.getChatCollection().subscribe(
      threads => this.thread$=threads
    )
  }

}