如何操纵Firebase数据分配给我的模型?

时间:2018-08-03 11:30:03

标签: javascript angular firebase rxjs angularfire2

**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; }'.

我已经尝试了很多小时来解决这个问题,但是我一直收到此错误。我无法观察到从firebase返回的数据类型以匹配我的模型。我该如何解决?

1 个答案:

答案 0 :(得分:0)

在集合上设置类型。

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

如果这不起作用,请将返回的对象定义为User而不是通用对象。

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