如何使用Angularfire以及async和Observables从Firebase正确读取数据?

问题描述 投票:0回答:1

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

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

我认为这与我处理Observable的方式有关,但是我真的很困惑。

这是我的代码:

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个回答
0
投票

此代码:

        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内部的代码。 。

© www.soinside.com 2019 - 2024. All rights reserved.