首页 > 解决方案 > 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)
      })
    })
}

标签: angulartypescriptfirebaserxjsrefactoring

解决方案


您的服务应该处理数据并对其进行整形:

 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;     
    })
}

推荐阅读