angular - RxJS 使用 snapshotChanges() 的方式是什么?
问题描述
所以我有一个 auth.service.ts、crud.service.ts 和一个 components.ts。虽然我编写的代码有效,但它恰好是多个教程和文档的组合。我想知道如何组合下面的代码以使其整洁,并且所有逻辑仅在 crud.service.ts 中使用 rxjs 运算符发生。最终结果将返回一个完全格式化的可观察项目集合。
crud.service.ts
getTasks() {
return this.auth.user$.pipe(
switchMap((value: any) => this.db.collection(`users/${value.uid}/tasks`).snapshotChanges())
)
}
component.ts
ngOnInit(): void {
this.fireService.getTasks().subscribe((a: any) => {
this.tasks = []
a.forEach((b: any) => {
let item: any = b.payload.doc.data();
item.id = b.payload.doc.id;
item.defaultState = true
this.tasks.push(item)
})
})
}
解决方案
您的服务应该处理数据并对其进行整形:
getTasks() {
return this.auth.user$.pipe(
switchMap((value: any) =>
this.db.collection(`users/${value.uid}/tasks`).snapshotChanges()),
map( (val) =>
val.map( (inner) => {
let item: any = b.payload.doc.data();
item.id = b.payload.doc.id;
item.defaultState = true;
return item;
}))
)
在您的订阅中,您只需分配值。
ngOnInit(): void {
this.fireService.getTasks().subscribe((a: any) => {
this.tasks = a;
})
}
推荐阅读
- python - 二维高斯函数不会产生正确的结果
- java - 当我尝试编译时,我的代码一直显示“需要数组,但找到了 java.lang.String”
- java - 无法解决 firebase-ui-auth
- llvm - 如何使用 UserOp1/UserOp2 指令?
- c# - 如何在图像单击时加载部分视图
- javascript - 在鼠标悬停按钮上:测试是否存在外部图像 url,如果存在则显示图像,如果不存在则显示 noimg.png
- google-cloud-dataflow - Google Cloud Shell - 如何解决 CERTIFICATE_VERIFY_FAILED 错误?
- .net - 如何将上传的 .CSV 文件发送到 Web 服务
- variables - 为变量分配初始值
- python - 当用户购买了某个类别时,寻找其他类别的销售?