javascript - 如何操作 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 获取返回的数据类型以匹配我的模型。我如何解决它?
解决方案
在集合上设置类型。
this.db.collection<User>('users')
如果这不起作用,请将返回的对象定义为 aUser
而不是通用对象。
let user: User = {
$key: doc.payload.doc.id,
...doc.payload.doc.data()
};
return user;
推荐阅读
- angular - Ionic 框架登录 API - 预检响应没有 HTTP ok 状态
- c# - 如何构造返回递归外键关系的实体框架查询
- iphone - iPhone 模拟器上没有声音 - xcode 10、Swift 4
- c# - 为什么 CancellationToken 是一个结构体?
- angular - 如何在 ionic 3 应用程序中禁用请求缓存或添加刷新?
- completable-future - Axon & CompletableFuture
- django - 如何在 Django 中为历史表设置自动生成的元字段
- google-sheets - 多个 IF(ISNUMBER(搜索不包括
- bash - 作为参数的文件的 Unix Bash 内容在第一行停止
- c# - MongoDB 和派生类