首页 文章

为什么始终从函数返回的值为null或未定义?

提问于
浏览
1

每当我运行以下代码时,checkIfUserHasMadeBet()函数返回的值总是为null . 似乎代码不是等待函数返回值而是等待跳过 . 如何让它等待函数从firebase数据库返回数据?

export class DisplayBetPage {
    hasCurrentUserMadeAbet: boolean = false;

    constructor(private navParams: NavParams, public navCtrl: NavController, private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase, public alertCtrl: AlertController) {
    }

   ionViewWillLoad() {
      var temp = this.checkIfUserHasMadeBet();
      console.log(temp); // comes out as null
      if (temp != null) {
         this.hasCurrentUserMadeAbet = true;
      }
   }

   checkIfUserHasMadeBet() {
       this.afAuth.authState.take(1).subscribe(auth => {    
           this.afDatabase.database
          .ref(`userprofile/${auth.uid}/bets/${this.bettingKey}`)
          .once(`value`).then(function(snapshot) {
                 console.log(snapshot.val()); 
                 // comes out with correct value [not null]
                return snapshot.val();
          });
       });
   }
}

1 回答

  • 3

    var temp = this.checkIfUserHasMadeBet(); 是异步调用,而您正在执行的 console.log(temp); 处于同步上下文中,因此在该调用之后,该值不会被解析并且为null .

    UPDATE

    有一些事情是错误的,首先要尝试实现这一点,最重要的是有一个服务来进行这种操作而不是在组件本身 .

    组件将调用服务方法,该方法将快照值保存在服务的 subjectbehaviour subject 中,然后您的组件将订阅该服务observable获取订阅中的快照值并执行所有必要的操作 .

    看看@ this link - 而不是使用Observables使用行为主题或重播主题在组件之间传递数据(共享服务) .

    按照这种方法将值传递给同一个组件,上面的链接就像一个要点,让你不遵循实际的答案 . 在您的方案中,没有观察或更新组件这两个组件都是一个组件 .

相关问题