如何在运行下一行代码Angular2之前等待AngularFire2订阅完成 [英] How to wait for a AngularFire2 subscription to finish before running the next lines of code Angular2

查看:251
本文介绍了如何在运行下一行代码Angular2之前等待AngularFire2订阅完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Angular2 Type Script代码有问题。我尝试通过订阅FirebaseListObserver来访问Firebase数据库中的问题:

  this.af。 list('/ questions')。subscribe(val => {
this.questions = val
console.log(this.questions)// works
})
console .log(this.questions)//显示未定义的

我不知道如何等待订阅在运行一个依赖于 this.questions 的函数之前获得一个值。



我尝试使用async /等待,但也没有等待订阅获得一个值。

我也尝试在一个承诺里面订阅,而且还返回一个空的数组。您可以从订阅回调中运行该函数,或者您可以在 questions 转换为setter / getter:

  private _questions = [] ; 

设置问题(问题){
this._questions = questions;

//对这里的问题做出反应
}

得到问题(){
return this._questions;





$ b如果你熟悉早期版本的话,的角度。因此,在 set 函数中,您可以检查 questions 是否有一个值并作出反应,调用所需的任何函数。

I have a problem with my Angular2 Type Script code. I'm trying to access Questions from a Firebase Database, which I am doing by subscribing to a FirebaseListObserver:

this.af.list('/questions').subscribe( val => {
     this.questions = val
     console.log(this.questions) // works
})
console.log(this.questions) // displays undefined

I dont know how to wait for the subscription to get a value, though, before running a function which depends on this.questions.

I tried to use async/await, but also didn't wait for the subscription to get a value.

I also tried to subscribe inside a promise, but also returned an empty array.

解决方案

You can either run the function from within the subscribe callback or you can turn questions into a setter/getter:

private _questions = [];

set questions(questions) {
  this._questions = questions;

  // React to questions changes here
}

get questions() {
 return this._questions;
}

Which will act kinda like a watcher if you're familiar with the early version of angular. So in the set function you can check if questions has a value and react to it, calling whatever function you need.

这篇关于如何在运行下一行代码Angular2之前等待AngularFire2订阅完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆