Ionic2使用AngularFire和Firebase时出错:未捕获(在promisse中):这是null

时间:2017-04-07 18:36:50

标签: firebase ionic-framework ionic2 angularfire2

我目前正在学习Ionic2和Angular,我正在尝试使用Firebase作为应用程序的数据库。我尝试做的第一件事是使用AngularFire使用Firebase Email身份验证进行登录。代码如下:

login.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Home } from '../../home/home';
import { SignUp } from '../signup/signup'
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2'
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class Login {
  constructor(public navCtrl: NavController, public af: AngularFire) {
  }
  public loginWithEmail(username: string, password: string) {
    this.af.auth.login({
      email: username,
      password: password,
    },
    {
      provider: AuthProviders.Password,
      method: AuthMethods.Password,
    }).then(function() {
      this.navCtrl.setRoot(Home);
    })
  }
}

的login.html

...
    <ion-list>
        <ion-item>
            <ion-label floating>Email</ion-label>
            <ion-input type="text" [(ngModel)]="userName"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Senha</ion-label>
            <ion-input type="password" [(ngModel)]="password"></ion-input>
        </ion-item>
        <ion-item>
            <button ion-button block (click)="loginWithEmail(userName, password)">Login</button>
        </ion-item>
    </ion-list>
...

但是,当我点击按钮并调用loginWithEmail()方法时,我收到以下错误:

Uncaught (in promise): TypeError: this is null
Login.prototype.loginWithEmail/<@http://localhost:8100/build/main.js:83566:13
O</g</t.prototype.invoke@http://localhost:8100/build/polyfills.js:3:9653
NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onInvoke@http://localhost:8100/build/main.js:37511:28
O</g</t.prototype.invoke@http://localhost:8100/build/polyfills.js:3:9591
O</d</e.prototype.run@http://localhost:8100/build/polyfills.js:3:7000
h/<@http://localhost:8100/build/polyfills.js:3:4659
O</g</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:10273
NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onInvokeTask@http://localhost:8100/build/main.js:37502:28
O</g</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:10201
O</d</e.prototype.runTask@http://localhost:8100/build/polyfills.js:3:7618
i@http://localhost:8100/build/polyfills.js:3:3700

我做错了什么?

2 个答案:

答案 0 :(得分:1)

  

但我仍然不知道为什么它会这样,而不是另一种...   有人可以解释一下吗?

答案是因为Arrow functions。在this之类的函数中使用function(){...}关键字时,this关键字引用函数本身(并且该函数中未定义navCtrl)。

箭头功能最重要的一个方面是

  

箭头函数表达式的语法短于函数   表达式和不绑定它自己的,参数,超级或   new.target。

因此,在()=&gt;中使用this关键字时{...},它仍将引用组件实例(其中定义了navCtrl属性),因此一切都按预期工作。

答案 1 :(得分:0)

好吧,我刚刚找到了让它运转的方法:我刚刚改变了:

(在login.ts上)

这样:

.then(function() {
  this.navCtrl.setRoot(Home);
})

到此:

.then(() => this.navCtrl.setRoot(Home))

但我仍然不知道为什么它会这样,而不是另一种......有人可以解释一下吗?