将Firebase数据库值推入新数组

时间:2019-01-02 08:28:11

标签: javascript typescript firebase ionic-framework firebase-realtime-database

我正在尝试通过Ionic打字稿文件将Firebase数据库值推入新数组。

问题是,我不断收到错误消息:

  

错误:未捕获(承诺):TypeError:无法读取未定义的属性'empList'

我真的不明白为什么,因为我还在学习打字稿,却不知道该怎么办。

firebase JSON如下所示:

pat = re.compile(r'[^\w\d\s,]+')
s = "we are \xaf\x06OK\x03family, good"
print(' '.join(map(lambda x: x.strip(), pat.split(s))))
#=> we are OK family, good

- users
  - hJfEgXkyaKPckchL3kx8rpZ58Ew2
    -LV6c8E5rRD4_mQqsb6Q
      - name: "Emily Blunt"
      - points: 20
      - grade: 12

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

问题的原因是this回调函数中firebase对象的作用域错误。它实际上是指Firebase.Promise。您需要保存对引用您的类的this的引用,然后在firebase回调中使用它:

export class Tab1Page {
  name: string;
  grade: number;
  points: number;
  empList: Array<{name: string, grade: number, points: number}> = [];

  constructor() {
    const usersRef = firebase.database().ref('/users/');
    const ref = usersRef.orderByChild('points');
    const self = this;
    ref.once('value').then(function(snap) {
      snap.forEach(function (childSnap) {
        const pkey = childSnap.key;
        // returns 'hJfEgXkyaKPckchL3kx8rpZ58Ew2'

        const keyRef = firebase.database().ref('/users/' + pkey);
        const ref2 = keyRef.orderByChild('name');

        ref2.once('value').then(function(snap) {
          snap.forEach(function (childSnap) {
            const key = childSnap.key;
            //returns -LV6c8E5rRD4_mQqsb6Q
            const firebaseRef = firebase.database().ref('/users/' + pkey + '/' + key);

            firebaseRef.once('value').then(function(snapshot) {
              const name = snapshot.val().name;
              const grade = snapshot.val().grade;
              const points = snapshot.val().points;
              // returns 'Emily Blunt', 12, 20
              self.empList.push({
                name: name,
                grade: grade,
                points: points
              });
            });
          });
        });
      });
    });
  }
}

您可以看到另一个SO答案,以获取有关this绑定的更多详细信息:How does the this keword work

相关问题