Home > Net >  Is there a way to write this function without returning a undefined
Is there a way to write this function without returning a undefined

Time:03-03

I'm using angular fire to read data on firestore based on the logged in user. I check that the user object has been returned, and based on this I have a command to listen to document changes.

async getUsersCards() {
  let _user: UserModel = await this.authService.GetUser();

  if (_user) {
    return this.angularFirestore
      .collection<Card>('cards', (ref) =>
        ref.where('owner', '==', _user?.uid)
      )
      .valueChanges();
  } else {
  }
}

Because I have a If check on the user, the signature of the function is Promise<Observable<board[]> | undefined> how do I remove the need for the undefined (what do I do in the else block ) ?

CodePudding user response:

I think you can simplify your code to return the Observable<Board[]> without the need to return a Promise, like the following:

// import { from, Observable } from 'rxjs';
// import { filter, mergeMap } from 'rxjs/operators';

getUsersCards(): Observable<Board[]> {
  // If `this.authService.GetUser()` returns an Observable, then you can use it directly without `from` function.
  // The `from` function is used to create an Observable from a Promise.
  return from(this.authService.GetUser()).pipe(
    filter((user) => !!user),
    mergeMap((user) =>
      this.angularFirestore
        .collection<Card>('cards', (ref) =>
          ref.where('owner', '==', user?.uid)
        )
        .valueChanges()
    )
  );
}

Then, in your component/service, you can use it like the following:

getUsersCards().subscribe((res: Board[]) => console.log(res));
  • Related