[AngularFire2 & Firestore] Example for collection and doc

import {Injectable} from '@angular/core';
import {Skill} from '../models/skills';
import {AuthService} from '../../auth/services/auth.service';

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
import {AngularFirestore, AngularFirestoreCollection} from 'angularfire2/firestore';


@Injectable()
export class SkillsService {

  skillCollection: AngularFirestoreCollection<Skill>;
  skills: Observable<Skill[]>;
  events: Observable<any>;

  constructor(private afs: AngularFirestore,
              private authService: AuthService) {

    this.skillCollection = afs.collection(`users/${this.uid}/skills`,
      ref => ref.orderBy('name').limit(10));
    this.events = this.skillCollection.auditTrail();
  }

  get uid() {
    return this.authService.user.uid;
  }

  getSkills(): Observable<Skill[]> {
    return this.skillCollection
      .snapshotChanges()
      .startWith([]) // To solve the snapshotChange doesn't fire for empty data
      .map((actions) =>
        actions.map(({payload}) => ({id: payload.doc.id, ...payload.doc.data()} as Skill))
      );
  }

  getSkill(key): Observable<Skill> {
    return this.afs.doc(`users/${this.uid}/skills/${key}`)
      .snapshotChanges()
      .map(({payload}) => ({id: payload.id, ...payload.data()} as Skill));
  }

  addSkill(skill: Skill) {
    return this.skillCollection.add(skill);
  }

  updateSkill(key: string, skill: Partial<Skill>) {
    return this.afs.doc<Skill>(`users/${this.uid}/skills/${key}`).update(skill);
  }

  removeSkill(key: string) {
    return this.afs.doc<Skill>(`users/${this.uid}/skills/${key}`).delete();
  }

}
原文地址:https://www.cnblogs.com/Answer1215/p/7770409.html