【问题标题】:Variable defined in subscription is undefined outside (Angular2, Firebase)订阅中定义的变量在外部未定义(Angular2,Firebase)
【发布时间】:2018-05-14 11:51:23
【问题描述】:

在我的 Angular2 组件 constructor 中,我将 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

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

我的dbAction 服务中的getDb()函数如下所示:

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

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

【问题讨论】:

  • 第一种情况肯定是异步的。您无法在块外访问来自 .subscribe 的回报。第二个问题似乎 .getDB() 由于某种原因没有定义。从这个 sn-p 很难确定那会是怎样的。 (即你永远不会执行 .subscribe。)
  • 我使用我的服务中的 getDb() 帮助函数编辑了我的帖子。 :)

标签: angular typescript firebase ionic2 angularfire2


【解决方案1】:

您可以将 observable 与 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})

【讨论】:

  • 我在哪里为我在视图中调用的 Observable 声明 this.visits
  • @eleinad 啊,你在 html 中使用异步管道吗?
  • @eleinad 啊,好吧,我误解了这个问题。你所拥有的应该工作,异步管道不会订阅this.visits,直到它在this.dbAction.getDB().take(1).subscribe 中定义。您收到的错误是 this.dbAction.getDB() 未定义,但我不确定它是如何未定义的
  • @eleinad 尝试将您的代码移动到 ngOnInit 而不是构造函数中
  • 我发现了问题!我的ngOnInit 中有this.visits.subscribe( () => this.spinner = false );,因为异步this.visits 仍然未定义。将此行移至this.dbAction.getDB().subscribe 使其工作!非常感谢您的帮助! :)
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2021-02-16
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多