0

I have user$: Observable<User>; in my AuthService. I hace OrderService too. I want to make request based on User.id (Getting all users orders).

This my function:

getUserOrders() {
    let id;
    this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);
    return this.firestore.collection('orders', ref => ref.where("purchaserId","==", id)).snapshotChanges().pipe(
      map(changes => {
        return changes.map(a => {
          let data = a.payload.doc.data() as Order;
          data.id = a.payload.doc.id;
          return data;
      });
      })
    );
  }

The problem is this line:

let id;
   this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);

Because id stays undefined when return statement is called. So i get error Function Query.where() requires a valid third argument, but it was undefined.

I know working with async pipe is convenient in html. But i think using observable in typescript makes it harder. I think better solution would be to change user$: Observable<User> to user: User.

1 Answer 1

1

This part is asynchronous :

this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);

So id isn't initialised yet with data.uid when firestore.collection is called.

You can change getUserOrders to :

return this.authService.user$.pipe(
  take(1),
  switchMap(({uid}) => {
    return return this.firestore.collection('orders', ref => 
      ref.where("purchaserId","==", uid)).snapshotChanges().pipe(
        map(changes => {
          return changes.map(a => {
            let data = a.payload.doc.data() as Order;
            data.id = a.payload.doc.id;
            return data;
          });
        })
      );
    })
  )

After getting the id, it switchs the returned observable to the firestore.collection with the provided id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.