【问题标题】:how to sync list from firestore collection realtime (component + service)如何从firestore集合实时同步列表(组件+服务)
【发布时间】:2019-10-08 07:00:24
【问题描述】:

我正在尝试在 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();

返回这个 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在我拥有用户之前激活的构造函数中)。

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

【问题讨论】:

  • ngFor 中删除async 管道。它会起作用吗?
  • 非常感谢!效果很好
  • 很高兴听到这个消息。实际上,建议根本不要订阅。我添加了这个问题的答案。

标签: angular typescript google-cloud-firestore angular-services


【解决方案1】:

问题的原因是您手动订阅了 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 方法返回的可观察对象,并保留模板中的async 管道:

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

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

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多