如何从FireStore获取收藏?

时间:2019-05-17 21:24:04

标签: angular firebase google-cloud-firestore

我正在尝试从Firestore检索整个集合,并按照说明逐步进行操作,但是始终有一些错误,无论是map()还是Observable或then()都不存在或无法正常工作。

这就是我一直试图得到的方式:


import { Injectable } from '@angular/core';
import { Employee } from './employee';
import { AngularFirestore } from '@angular/fire/firestore';

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

  FormData: Employee;

  constructor(private firestore: AngularFirestore) { }

  getEmployees(){
    this.firestore.collection('employees').get().then((snapshot) => {
      snapshot.docs.forEach(doc => {
        console.log(doc);
      })
    })
  }
}


这就是我现在得到的:

src / app / employees / shared / employee.service.ts(16,50)中的错误:错误TS2339:“ Observable”类型上不存在属性“ then”。

1 个答案:

答案 0 :(得分:1)

请尝试以下操作,而不要使用valueChanges()valueChanges()返回数据的Observable作为JSON对象的同步数组。

getEmployees(){
  this.firestore.collection('employees')
    .valueChanges()
    .subscribe(docs => {
      // loop through each item in the array and log value
      docs.forEach(doc => console.log(doc));
    });
}

这来自valueChanges()的文档。如果需要文档ID,可以将snapshotChanges()与RxJS可管道运算符(例如map())结合使用(以创建具有ID和数据的对象数组):

getEmployees(){
  this.firestore.collection('employees')
    .snapshotChanges()
    .pipe(
       map(actions => actions.map(a => {
         const data = a.payload.doc.data();
         const id = a.payload.doc.id;
         return { id, ...data };
       });
    )
    .subscribe(docs => {
      // loop through each item in the array and log value
      docs.forEach(doc => console.log(doc.id));
    });
} 

理想情况下,您应该创建一个classinterface来表示每个“雇员”的数据结构,并使用该结构强烈地键入响应:

服务:

interface Employee {
  someProperty: number;
  anotherProperty: string;
  yetAnotherProperty: boolean;
}

// ...

// perhaps return the observable so a component using this service can consume the data (can't return from inside subscribe())
getEmployees(): Observable<Employee[]> {
  return this.firestore.collection<Employee>('employees').valueChanges();

  /* or instead snapshotChanges() with map()
    return this.firestore.collection<Employee>('employees')
      .snapshotChanges()
      .pipe(
        map(actions => actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data };
       });
    )
  */
}

组件:

@Component({ /* ... */})
export class SomeComponent {
  constructor(private employeeService: EmployeeService) {}

  ngOnInit() {
    this.employeeService.getEmployees().subscribe(employees => console.log(employees));
  }
}

希望有帮助!