javascript - Ionic 2,this.nav.push() 未定义

标签 javascript ionic-framework angular ionic2

我来自 Ionic 1,我从 ionic 2 开始。 当我在 promise 之后立即使用 this.nav.push(nameOftheOterPage) 时出现错误,但是当我在 promise 函数 authHandler 之外使用它时,这个函数 this.nav.push 完全正常工作:

    import {Page, NavController} from 'ionic-angular';
    import {ItemDetailsPage} from '../item-details/item-details';

    @Page({
      templateUrl: 'build/pages/login/login.html'
    })
    export class LoginPage {
      static get parameters() {
        return [[NavController]];
      }

      constructor(nav) {
        this.nav = nav;
        this.firebaseUrl = "https://MYFIREBASE.firebaseio.com";
        this.authType = "login";
        this.error_username = false;
      }

      login(form) {
      if(form.controls.username.value === null){

        this.error_username = true;
      }
      else{
          /* Authenticate User */ 
          var ref = new Firebase(this.firebaseUrl);
          ref.authWithPassword({
            email    : form.controls.username.value,
            password : form.controls.password.value
          }, this.authHandler);
          }
        }

      authHandler(error, authData) {
        if (error) {
            console.log("Login Failed!", error);
        } else {
            console.log(authData);
            this.nav.push(ItemDetailsPage);
        }
      }
    }

你能帮我吗?

谢谢。

最佳答案

this 的使用在 javascript 对象中有点棘手,尤其是当涉及到回调时。 (我推荐这个 interesting article 关于它)。

要点是,您始终需要跟踪调用函数的对象,因为 this 将绑定(bind)到调用对象。

您的问题的解决方案是 bind你的类的 this 到回调,这样 this 就会是你认为应该的样子。因此,当您调用 authWithPassword 时,请按如下方式进行:

ref.authWithPassword({
   email: form.controls.username.value,
   password: form.controls.password.value
}, this.authHandler.bind(this));

编辑
正如@Manu Valdés 在评论中建议的那样,如果您想避免使用 bind,您还有另一种选择,即按以下方式定义 authHandler:

authHandler = (error, authData) => {
    if (error) {
        console.log("Login Failed!", error);
    } else {
        console.log(authData);
        this.nav.push(ItemDetailsPage);
    }
}

之所以有效,是因为在 arrow functions 中, 它们的 this 被设置为外部执行上下文的那个,不管调用者是谁。

关于javascript - Ionic 2,this.nav.push() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37399152/

相关文章:

android - Cordova /Ionic2 |如何锁定和解锁Android和iOS的屏幕?

css - ionic 应用程序没有响应需要 scss 的帮助

android - 状态栏隐藏 Cordova

javascript - Angular 2 http 服务中的访问控制允许来源问题

javascript - Angular2 Component 循环渲染 2 个 tr 元素

c# - CORS 预检选项请求从 Windows 身份验证的 web api 返回 401(未经授权)

javascript - 转换 jQuery 对象中的 lodash/下划线集合(链接)

javascript - 如何检测新全局变量的创建?

javascript - 如何检查 Vuejs v-if 中的数组元素是否相等?

javascript - XAMPP 返回错误 "Unexpected end of JSON input"