【问题标题】:How use correctly the NavController component [duplicate]如何正确使用 NavController 组件 [重复]
【发布时间】:2018-03-01 23:53:43
【问题描述】:

我需要这样做:

  async doLogin(user: User) {
    try {
      const result = await this.AngularFireAuth.auth.signInWithEmailAndPassword(user.email, user.password);
      if (result) {
        this.AngularFireAuth.authState.subscribe(user => {
          if (user) {
            var ref = firebase.database().ref(`profile/${user.uid}`);
            ref.once("value")
              .then(function(snapshot) {
                var key = snapshot.key;
                if (user.uid === key) {
                  this.navCtrl.setRoot(HomePage);
                }
                else {
                  this.navCtrl.setRoot(ProfilePage);
                }
              });
          }
        });
      }
    }
    catch (error) {
      let toast = this.toastCtrl.create({
        message: this.loginErrorString,
        duration: 3000,
        position: 'top'
      });
      toast.present();
    }
  }

但我收到了这个错误:TypeError: Cannot read property 'navCtrl' of undefined

我不知道为什么会这样,但我认为 doLogin 方法无法读取模块 navCtrl。明显增加了navCtrl方法构造。

最好的问候朋友

【问题讨论】:

  • .then(function(snapshot) {改成箭头函数。 function 关键字创建一个新的 this 上下文

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


【解决方案1】:

首先,尝试使用箭头函数(snapshot) => {...} 而不是常规的function(snapshot) {...}。在您的情况下,您使用的是 this 关键字,因此旧函数存在许多问题,这些问题已在新的 ES6 箭头函数中得到解决!

有关箭头函数的更多信息和thishttps://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

【讨论】:

  • 谢谢!我研究了箭头函数,这没有问题
猜你喜欢
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-15
  • 2017-11-16
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多