我目前有一个Firestore文档查询,如下所示:
getDocument(){
this.albumDoc = this.afs.doc<Album>(`albums/abc`);
this.album = this.albumDoc.valueChanges();
}
AngularFire文档指出您可以使用“快照”更改来获取更多数据。但是,没有如何执行此操作的示例。对于集合查询,快照更改使用管道/映射,然后返回“数据”,然后可以根据需要将其分配给变量。
是否可以对文档查询执行相同的操作?我的文档中有一个Firestore值,我想用它来取笑。
答案 0 :(得分:1)
valuechanges()和snapshotChanges()之间的主要区别在于,后者为我们提供了分配给文档的唯一文档ID,而前者仅为我们提供了文档值,而没有给我们提供ID。
如果可能,我正在分享一个示例尝试:
这是我的服务文件:
import { Injectable } from '@angular/core';
import { Employee } from './employee.model';
import { AngularFirestore } from '@angular/fire/firestore';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
formData: Employee;
constructor(private firestore: AngularFirestore) { }
getEmployees() {
return this.firestore.collection('employees').snapshotChanges();
}
}
这是我的component.ts文件:
import { Component, OnInit } from '@angular/core';
import { Employee } from 'src/app/shared/employee.model';
import { EmployeeService } from 'src/app/shared/employee.service';
import { AngularFirestore } from '@angular/fire/firestore';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
list: Employee[];
constructor(private service: EmployeeService, private firestore: AngularFirestore) { }
ngOnInit() {
this.service.getEmployees().subscribe(actionArray => {
this.list = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Employee
})
});
}
onEdit(emp: Employee) {
this.service.formData = Object.assign({},emp);
}
onDelete(id: string) {
if(confirm("are you sure you want to delete this record ?")) {
this.firestore.doc('employees/' + id).delete();
}
}
}