'Joining' Firebase Queries in Angularfire2

前端 未结 2 957
旧巷少年郎
旧巷少年郎 2021-01-02 20:12

Update:

The issues I was encountering with the empty value fields had to do with non-existent keys in my database, so most of the discourse here won\'t apply to yo

2条回答
  •  渐次进展
    2021-01-02 21:05

    To solve joins on users, I wrote a service that caches the users already fetched and maps them into the referencing data with minimal code. It uses a nested map structure to do the join:

    constructor(public db: AngularFireDatabase, public users:UserProvider) {
        this.threads = db.list('threads').valueChanges().map(messages => {
          return threads.map((t:Message) => {
            t.user = users.load(t.userid);
            return m;
          });
        });
    }
    

    And the UserProvider service looks like so:

    @Injectable()
    export class UserProvider {
      db: AngularFireDatabase;
      users: Map>;
    
      constructor(db: AngularFireDatabase) {
        this.db = db;
        this.users = new Map();
      }
    
      load(userid:string) : Observable {
        if( !this.users.has(userid) ) {
          this.users.set(userid, this.db.object(`members/${userid}`).valueChanges());
        }
        return this.users.get(userid);
      }
    }
    

    There's a complete working example of the joins and all the boilerplate here

提交回复
热议问题