angularfire switchMap,添加了子元素,然后将结果输入另一个方法

时间:2020-08-13 22:15:53

标签: javascript angular firebase-realtime-database angularfire switchmap

我正试图将我几年前编写的此功能移植到angularfire中,但会遇到一些困难:

它通过电子邮件地址对结果进行排序,对于找到的每个孩子,然后获得对数据库中某个位置的新引用,即 / AIS / USERSAVEDCONFIGS /'+ userId ,然后针对< em>那个列出它可以做的事情

var usersRef = firebase.database().ref('/USERS/');

usersRef.orderByChild("EMAIL").startAt(email).endAt(email+"\uf8ff").on("child_added", function(userAccountSnapshot) {
    //The users are indexed by their uID. We can therefore obtain it by getting the key
    var userId = userAccountSnapshot.ref.key;
    //Get the user saved configs for this user
    var userSavedConfigs = firebase.database().ref('/AIS/USERSAVEDCONFIGS/'+ userId);
    userSavedConfigs.on("child_added", function(usersSnapshot) {
       //Do stuff
    });
});

按照angularfire文档指南进行操作后,我变得有些困惑,我已经明白了这一点,并且能够获取用户列表,但是我无法弄清楚如何将该列表传递到另一个引用中。如果确实的话,我应该首先这样做。

this.users$ = new BehaviorSubject(null);
this.items$ = this.users$.switchMap(email => 
  db.list('/USERS/', ref => 
  email ? ref.orderByChild('EMAIL').startAt(email).endAt(email+"\uf8ff") : ref
  ).snapshotChanges()
);

我尝试像这样添加on(...),但编译器似乎并不喜欢

email ? ref.orderByChild('EMAIL').startAt(email).endAt(email+"\uf8ff").on(...) 

实现此目标的最佳方法是什么?

几个小时后,我能够像这样取出数据,但是-我认为它非常糟糕,因此希望能有一些改进建议。我坚决可以将它做得更加多汁。我敢肯定,将输出泵送到单独的数组中也不是处理输出的最佳方法,至少是所有方法都不是,因为这意味着每次数据更改时我都必须手动擦除它:

this.users$ = new BehaviorSubject(null);
this.userIds$ = this.users$.switchMap(email =>
  db.list('/USERS/', ref => {
    let temp = email ? ref.orderByChild('EMAIL').startAt(email).endAt(email + "\uf8ff") : ref
    console.log('carrot');
    return temp;
  }
  ).snapshotChanges()
);

//Subscribe to the output of user ids, when we get a hit (delivered as an array of references) loop through and subscribe to all the children of this location
this.userIds$.subscribe(
  (references) => {
    references.forEach((reference) => {
      db.list('/AIS/USERSAVEDCONFIGS/' + reference.key).snapshotChanges(['child_added']).subscribe(actions => {
        actions.forEach(action => {
          console.log(action.type);
          console.log(action.key);
          console.log(action.payload.val());
          this.userConfigsArray.push(action.payload.val());
        });
      });
    });
  },
  console.error,
  () => console.log('complete')
);

0 个答案:

没有答案