user9847788
user9847788

Reputation: 2431

How to resolve Promise mismatch in Angular / Typescript app?

I am trying to retrieve a User object from Firestore in my Angular app.

User model:

import { PlaceLocation } from './location.model';

    export class User {
        constructor(
            public userId: string,
            public userName: string,
            public isMechanic: boolean,
            public location: PlaceLocation
        ) { }
    }

Component:

user: User;

this.usersService
    .getUserByUserId(paramMap.get('id'))
    .subscribe(user => {
        this.user = user;
});

Users Service:

getUserByUserId(userId: string) {
    return of(
      firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
        .then((querySnapshot) => {
          console.log("Query Snapshot:", querySnapshot);
        }).catch((err) => {
          console.log("Query Error:", err);
        })
    );
  }

But I'm getting this compilation error when I try to assign this.user = user:

Type 'Promise' is missing the following properties from type 'User': userId, userName, isMechanic, location

Can someone please tell me what changes are required to resolve this issue?

Upvotes: 0

Views: 67

Answers (2)

Alexey Sviridov
Alexey Sviridov

Reputation: 68

"from(...promise...)" solution will not always work. Promise could resolve before you soubscribe on.

True way is make observable at first:

getUserByUserId(userId: string) {
  return new Observable<any>((observer: Observer<any>) => {
    firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
        .then((querySnapshot) => {
          observer.next(querySnapshot);
          observer.complete();
        }).catch((err) => {
          observer.error(err);
        })

  });
}

Upvotes: 0

bryan60
bryan60

Reputation: 29355

you're returning an observable of a promise... think you want from, which converts a promise into an observable.

  getUserByUserId(userId: string) {
    return from(
      firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
    ).pipe(
      map(querySnapshot => { ... do transform ... }),
      tap( // handle errors / logging in observable fashion
        query => console.log(query, 'success),
        error => console.log(error, 'error')
      ),
      // catchError(error => { ... do something with error ... })
    );
  }

Upvotes: 1

Related Questions