【问题标题】:Angular 4 firebase read a value from database and pass it to the programAngular 4 firebase 从数据库中读取一个值并将其传递给程序
【发布时间】:2017-08-04 04:35:24
【问题描述】:

我在 Firebase 数据库中使用 Angular 4 和 angularfire。我有以下 Firebase 数据库

"questions" : {
"tv" : {
  "got" : {
    "1" : {
      "answer1" : "Death",
      "choice11" : "Exile",
      "choice12" : "You lose a hand",
      "choice13" : "You lose the privilege to marry and father children",
      "description" : "",
      "q1title" : "What is the punishment for deserting the Night’s Watch?"
    },
    "questions" : {
      "number" : 1
    }
  }
}
}

我想读取按钮上的问题编号并将其传递给我的程序以在函数等上使用它。我目前正在使用这部分代码来读取它

constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
              private router: Router) {
    var ref = firebase.database().ref("questions/tv/got/questions");
    ref.once("value")
      .then(function(snapshot) {
        let qnumber = snapshot.child("number").val(); 
        console.log(qnumber);
      });
  } 

一切正常,我可以在 concole 上看到 qnumber(qnumber=1)。但是我无法在程序上传递 qnumber 并将其用于我的其他功能 我试图声明第二个变量,并像这样给它 qnumber 值

    qnumber2;
  constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
              private router: Router) {
    var ref = firebase.database().ref("questions/tv/got/questions");
    ref.once("value")
      .then(function(snapshot) {
        let qnumber = snapshot.child("number").val(); 
        this.qnumber2 = qnumber;
        console.log(qnumber2);
      });

但是我在编译器上遇到错误。您能帮我告诉我一种将程序中的 qnumber 作为整数传递的方法吗?

【问题讨论】:

    标签: javascript angular typescript firebase firebase-realtime-database


    【解决方案1】:

    试试这个:

    qnumber2;constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase,public authService: AuthService,
              private router: Router) {
    var ref = firebase.database().ref("questions/tv/got/questions");
    ref.once("value")
      .then((snapshot) => {// ** My only change ** or use snapshot
        let qnumber = snapshot.child("number").val(); 
        this.qnumber2 = qnumber;
        console.log(qnumber2);
      });
    

    this 关键字指的是函数所属的对象,或者 如果函数不属于任何对象,则为窗口对象。在 JavaScript 中,函数是一个对象。 for more on this inside a function

    在您的情况下 this.qnumber2 不是全局的,它的范围仅限于它使用的功能。如果你不使用任何函数,那么 this 将引用全局对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多