javascript - Ionic 2 Angular 2 - 无法从方法访问 NavController

标签 javascript ionic2 ionic3 lexical-scope

用户通过 AngularFire 进行身份验证后,我正在尝试导航到另一个页面。除了导航到另一个页面之外,一切正常。

这是我的代码:

  constructor(public navCtrl: NavController, public menu: MenuController, public afAuth: AngularFireAuth, public db: AngularFireDatabase, private platform  : Platform) {
    this.navigateIfUserIsLogdIn();
  }

  navigateIfUserIsLogdIn(){
        this.authState = this.afAuth.authState;
        this.user = this.afAuth.auth.currentUser;

        this.afAuth.auth.onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            this.navCtrl.setRoot(HomePage);
          } else {
            // No user is signed in.
          }
        });
  }

我得到的错误是:

错误:未捕获( promise 中):TypeError:无法读取未定义的属性“navCtrl”

为什么在 navigatorIfUserIsLogdIn() 内部时它不起作用?

请帮忙,并提供一个例子:)

最佳答案

您需要使用这样的箭头函数:

navigateIfUserIsLogdIn(){
    this.authState = this.afAuth.authState;
    this.user = this.afAuth.auth.currentUser;

    this.afAuth.auth.onAuthStateChanged((user) => {
      if (user) {
        // User is signed in.
        this.navCtrl.setRoot(HomePage);
      } else {
        // No user is signed in.
      }
    });
}

请注意,现在我们这样做

this.afAuth.auth.onAuthStateChanged((user) => {...});

而不是

this.afAuth.auth.onAuthStateChanged(function(user) {

通过使用箭头函数,this 属性不会被覆盖,并且仍然引用组件实例(否则,this 关键字指向内部函数,并且 navCtrl 未在其中定义)。

关于javascript - Ionic 2 Angular 2 - 无法从方法访问 NavController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44317456/

相关文章:

node.js - Ionic2 应用程序从 Mac 移至 PC 导致构建问题

angular - Ionic 3 和 Ngzone 不工作 - 不将结果更新为 HTML View

javascript - 如何在 Angular 中获取所选选项的索引

javascript - 每次在 jQuery 中加载元素时,如何让 .ready 被调用?

javascript - jQuery 突出显示 href 值以外的单词

javascript - 谷歌闭包编译器javascript解析错误

javascript - JS 变量在 Ionic 中不起作用

javascript - 如何使用 jQuery 打印文档中的表格内容?

css - 将图像设置为标准尺寸

angular - 从子 @Input setter 访问提供者方法 - Ionic2/Angular2