订阅中定义的变量在外部未定义(Angular2,Firebase)

时间:2017-11-30 14:04:58

标签: angular typescript firebase ionic2 angularfire2

在我的Angular2组件构造函数中,我将Firebase中的值存储到变量中。

this.dbAction.getDB().take(1).subscribe(data => {
  this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder']; 
  console.log(this.userVisitOrder); // Value exists
});

我需要该变量才能构建我的Observable以使用特定的firebase数据。也在我的构造函数中:

this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); // Here the value is undefined

我认为这是一个异步问题,但我怎样才能访问存储在变量中的数据?

getDb()服务中的dbAction功能如下所示:

getDB() {
  return this.afDatabase.list(`data`).valueChanges().map((data) => data);
}

如果我尝试将第二个代码放入第一个代码:

this.dbAction.getDB().take(1).subscribe(data => {
  this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];

  this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder));
  this.visits = this.visitsRef.snapshotChanges().map(changes => {
    return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
  });
});

...我收到以下控制台错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将观察者与switchMap链接起来,以便一个接一个地运行。

this.dbAction.getDB().take(1)
    .switchMap(data => {
        this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];

        this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder));

        return this.visitsRef.snapshotChanges();
    })
    .map(changes => {
        return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
    .subscribe(res => {// do something with result})