【问题标题】:How would the structure be to obtain the following data structure from firebase?该结构将如何从firebase获取以下数据结构?
【发布时间】:2020-01-15 00:19:26
【问题描述】:

这是我想从 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};
    }))
);

如何制作 interfacequerys 以从 firebase 获取此结构??

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore


    【解决方案1】:

    你可以使用泛型类型来创建这样的东西:

    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())
    

    通过这种方式,您可以指定对象的类型,并且仍然有一种通用且可预测的方式来处理您的数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多