首页 > 解决方案 > 如何操作 Firebase 数据以分配给我的模型?

问题描述

**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 observable 获取返回的数据类型以匹配我的模型。我如何解决它?

标签: javascriptangularfirebaserxjsangularfire2

解决方案


在集合上设置类型。

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

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

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

推荐阅读