Search code examples
javascriptangularfirebaserxjsangularfire2

How to manipulate Firebase data to assign to my model?


**Model:**

export interface User {
    $key?: string;
    firstname: string;
    lastname: string;
    id: number;
    age: number;
}

**Angular service:**

public fetchAvailableUsers(): void {
      this.firebaseSubscriptions.push(this.db.collection('users')
         .snapshotChanges()
         .pipe(
            map(docArray => {
                  return docArray.map(
                    return {
                        $key: doc.payload.doc.id,
                        ...doc.payload.doc.data()
                    };
                });
            })
         )
         .subscribe((users: User[]) => {
            this.store.dispatch(new fromUser.SetUsers(users));
         }, error => {
         ...
      }));
   }

**Error:**

Argument of type '(users: User[]) => void' is not assignable to parameter of type '(value: { $key: string; }[]) => void'.
Types of parameters 'users' and 'value' are incompatible.
Type '{ $key: string; }[]' is not assignable to type 'User[]'.
Type '{ $key: string; }' is not assignable to type 'User'.
Property 'firstname' is missing in type '{ $key: string; }'.

I've tried so many ways for hours to get around it but I keep getting this error. I can't get the returned data type from firebase observable to match my model. How do I fix it?


Solution

  • Set a type on the collection.

    this.db.collection<User>('users')
    

    If that doesn't work, define the returned object as a User instead of a generic object.

    let user: User = {
      $key: doc.payload.doc.id,
      ...doc.payload.doc.data()
    };
    return user;