如何从 firestore 集合实时同步列表(组件+服务)

how to sync list from firestore collection realtime (component + service)

我试图在 html 页面中将 firestore 集合呈现为列表,首先我从我的组件在列表上创建 Observable,它工作正常但我意识到它应该在服务中,我改变了我的代码:

在服务构造函数中:

this.tenantCollection = this.angularFirestore.collection('landlord').doc(this.user.uid).collection("tenants", ref => {
              return ref.orderBy('name')})
this.tenantsList = this.tenantCollection.valueChanges();

并函数 return 这个 Observable(也在服务中):

getTenants(){
  return this.tenantsList;
}

组件:

constructor(private landlordService: LandlordService, private router: Router, private route: ActivatedRoute,
    private angularFirestore: AngularFirestore, private auth: AuthService) {
   this.auth.user.subscribe(user => {
        if (user) {
            this.user = user;              
    this.landlordService.getTenants().subscribe(tenanes => {
        this.tenants = tenanes;
        console.log(this.tenants);
    });
        }
    });

html:

<app-tenant-item *ngFor="let t of tenants | async; let i= index" [tenant]="t" [index]="i">
    </app-tenant-item>

尽管以这种方式 firestore 中有值,但此列表始终为空(我将订​​阅放在 ngOnInit 在我拥有用户之前激活的构造函数中)。

如何修复它并实时获得更改?

问题的原因是您手动订阅了 landlordService.getTenants 方法返回的 observable。所以现在,tenants 变量保存原始数据,而不是可观察数据。

您需要删除 async 管道:

<app-tenant-item *ngFor="let t of tenants; let i= index" [tenant]="t" [index]="i">
</app-tenant-item>

或将 tenants 变量分配给 landlordService.getTenants 方法 returns 和 keep 中的 async 管道模板:

this.tenants = this.landlordService.getTenants();

首选第二种方法,因为您不需要手动取消订阅以避免内存泄漏。有关此的更多信息:https://blog.angularindepth.com/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794 .