【问题标题】:How to properly read out data from the firebase using Angularfire and async and Observables?如何使用 Angularfire 和 async 以及 Observables 从 firebase 中正确读取数据?
【发布时间】:2020-05-06 03:53:58
【问题描述】:

我正在尝试从 Firebase 中读取数据,在一个简单的查询中,我通过提供的名称检索组织。

我面临的挑战是查询工作正常并且可以检索数据,但是在执行流程中,读取实际数据的逻辑启动得太晚了。

我认为这与我处理 Observables 的方式有关,但我真的被卡住了。

这是我的代码:

async getOneOrganizationByName(name: string) {
        console.log("2. Doing the check");
        const query = this.afs.collection<Organization>('organizations', ref => ref.where('name', '==', name).limit(1));

        return query.snapshotChanges().pipe(
            debounceTime(500),
            take(1),
            map(
                changes => { 
                    return changes.map(a => {
                        const data = a.payload.doc.data() as Organization;
                        data.id = a.payload.doc.id;
                        console.log("3. From the check logic: " + data.name);   
                        return data;
                    });
                }
            )
        );
    }

    async nameExists(name: string) {
        if(_.isNil(name)) {
            return false;
        }
        console.log("1. Before the check");

        let foundName: string;

        (await this.getOneOrganizationByName(name)).subscribe((organizations: Organization[]) => {
            foundName = organizations[0].subdomain;
            console.log("4. Set item: " + organizations[0].subdomain);
        });

        console.log("5. Found item: " + foundName);

        if(_.isNil(foundName)) {
            console.log("6. return false")
            return false;
        }
        console.log("6. return true")
        return true
    }

从上面的代码中,我希望在控制台输出中看到:1、2、3、4、5、6 以及相应的消息,但我得到 1、2、5、6、3、4。

如何确保在数据被读出之前阻塞逻辑的执行?

【问题讨论】:

  • 将代码放入订阅回调中。

标签: angular firebase async-await observable angularfire


【解决方案1】:

这段代码:

        console.log("5. Found item: " + foundName);

        if(_.isNil(foundName)) {
            console.log("6. return false")
            return false;
        }
 console.log("6. return true")

需要在subscribe 回调中。由于Observables用于异步代码,所以当你检索数据时,subscribe之后的代码会被调用first,当数据被完全检索到之后,subscribe里面的代码会被调用。将被调用。

【讨论】:

  • 谢谢,确实效果很好。另一个后续问题......如何以同步方式从组件调用“nameExists”方法?我有以下console.log("Before"); this.myService.nameExists(name); console.log("After");,我想输出Before,1,2,3,4,5,6,After,但我得到Before,After,1,2,3,4,5,6
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多