0
\$\begingroup\$

I wanted to check and see if this was as efficient as can be. The goal is to get a user's data from a group of documents that contains references to users in Firestore.

ngOnInit

this.links = this.currentUserRef.collection('links', ref => ref.where('pendingRequest', '==', false)).get()
            .pipe(map(querySnap => {
                const ret = [];
                querySnap.forEach(async doc => {
                    const val = await doc.get('otherUser').get().then(async userData => {
                        return {
                            id: userData.id,
                            img: await this.getImage(userData.get('profilepic')),
                            name: userData.get('name'),
                            bio: userData.get('bio')
                        }
                    });
                    ret.push(val);
                });
                return ret;
            }));

HTML

<ion-item *ngFor="let link of links | async">
            <ion-avatar slot="start">
                <img src="{{link.img}}">
            </ion-avatar>
            <ion-label>
                <h2>{{link.name}}</h2>
                <p>{{link.bio}}</p>
            </ion-label>
            <ion-checkbox id="{{link.id}}"></ion-checkbox>
        </ion-item>
\$\endgroup\$
0
\$\begingroup\$

What do you mean with "efficient" in this case?

From the performance perspective its slow, because it handles one element after the other and for handling one element it needs to wait for an async call.
As a result the browser will note be able to execute multiple requests at once.

You could try to move the getImage request into the html with the async pipe. Then the browser will be able to fire multiple requests simultaniously.

Beside that i personaly would divide the code in a few methods. So it would look like this:

__HTML__
<img [src]="getImage(link.img) | async"



__TypeScript__
interface Link{
    id: string,
    img: string,
    name: string,
    bio: string
};

...
this.links = this.getLinks(userRef);
...

private getLinks(userRef: ??? ): Link[] {
    return userRef.collection('links', ref.where('pendingRequest', '==', false)).get()
        .pipe(
            map(querySnap => mapSnapToLinks(querySnap))
        )
}

private mapSnapToLinks(querySnap: ???):Link[]{
    querySnap.forEach(async doc => {
        const val = doc.get('otherUser').get().then(userData => this.mapUserToLink(userData));
        ret.push(val);
    });
}

private mapUserToLink(userData): Link {
    return {
        id: userData.id,
        img: userData.get('profilepic'),
        name: userData.get('name'),
        bio: userData.get('bio')
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.