google-cloud-firestore - AngularFire - 如何使用快照更改并将数据作为变量返回
问题描述
我目前有一个 Firestore 文档查询,如下所示:
getDocument(){
this.albumDoc = this.afs.doc<Album>(`albums/abc`);
this.album = this.albumDoc.valueChanges();
}
AngularFire 文档声明您可以使用“快照”更改来获取更多数据。但是,没有示例说明您将如何执行此操作。对于集合查询,快照更改使用管道/映射,然后返回“数据”,然后您可以根据需要将其分配给变量。
是否可以对文档查询做同样的事情?我的文档中有一个 Firestore 值,我想抓取和玩弄它。
解决方案
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();
}
}
}
推荐阅读
- kubernetes - 触发 kubernetes HPA 自动缩放后是否有任何 webhook 或事件
- mysql - sql 行值作为列?
- selenium - 自动化测试 - Selenium WebDriver - 运行多个测试用例
- sql - 如何在 SQL (postgres) 中找到与年度最大资源相关的项目 ID?
- python - django API如何获取参数包括特殊字符
- python-3.x - 用于 Tensorflow 的 Kubernetes OOMKilled 容器
- python - 如何与条形图一起显示百分比
- microsoft-teams - Teams Tab API 访问 Sharepoint 文件内容导致 405 选项调用
- javascript - 当节点js中的休息调用失败时如何超时功能?
- c# - 在 C# Mono 中以编程方式访问 Unity sharedassets.assets 文件中的项目