[英]How would the structure be to obtain the following data structure from firebase?
这是我想从 firebase 获得的结构,它要求我提供一个接口来格式化答案,这是正确的还是如何正确的?
{
"users":{
"user1":{
"username":"john",
"full_name":"John Vincent",
"created_at":"9th Feb 2015",
"groups":{
"group1":true,
"group3":true
}
"last_logins":...
},
"user2": ...,
"user3": ...
}
"groups": {
"group1"{
"group_name":"Administrators",
"group_description":"Users who can do anything!",
"no_of_users":2,
"members":{
"user1":true,
"user3":true
}
},
"group2"{
"group_name":"Moderators",
"group_description":"Users who can only moderate!",
"no_of_users":1,
"members":{
"user2":true
}
}
}
}
这是我的代码...!!!
export interface Users {
username: string;
full_name: string;
created_at: string;
groups: any[];
}
export interface Group {
group_name: string;
group_description: string;
no_of_users: Number;
members: any[];
}
this.users = this.db.collection('users').snapshotChanges().pipe(
map(actions =>
actions.map(a => { const data = a.payload.doc.data() as Users; const id = a.payload.doc.id;
return {id, ...data};
}))
);
this.groups = this.db.collection('groups').snapshotChanges().pipe(
map(actions =>
actions.map(a => { const data = a.payload.doc.data() as Group; const id = a.payload.doc.id;
return {id, ...data};
}))
);
如何使接口和查询从firebase获取此结构?
您可以使用泛型类型来创建这样的东西:
export class FirebaseService<T> {
constructor (collection: string) {
this.dbInstance = fireDb //import
this.collection = collection
}
.
.
.
async list(): Promise<T[]> {
return this.dbInstance
.collection(this.collection)
.get()
.then(async querySnapshot => {
const result: Array<T> = [];
querySnapshot
.forEach(doc =>
result.push(doc.data())
)
return result;
})
}
}
并像这样使用它
const service = new FirebaseService<User>('Users');
console.log(await service.list())
通过这种方式,您可以指定对象的类型,并且仍然有一种通用且可预测的方式来处理您的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.