ionic 3 "TypeError: this is null"

ionic 3 "TypeError: this is null"

当我从 firebase 获取数据时,我正在尝试重定向。 如果它为 null 或空则无需重定向。

我正在尝试使用 this.navCtrl.push(ProspectPage); 但不知道为什么它不起作用 它 returns 一个错误

TypeError: this is null

这是我的代码,请检查它并让我知道我在这里做错了什么。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ProspectPage } from '../prospect/prospect';
import * as firebase from 'firebase';

@Component({
  selector: 'page-credentials',
  templateUrl: 'credentials.html'
})
export class CredentialsPage {
  constructor(public navCtrl: NavController) {
}

register(params){
// this.navCtrl.push(ProspectPage); // if i wrote here then it works
  ref.orderByChild("ssn").equalTo(1234).on("value", function(snapshot) {
    if(snapshot.val())
    {
      this.navCtrl.push(ProspectPage);
    }
   });
  }
 }

查看 register() 有一条评论。如果我在函数的开头添加 this.navCtrl.push(ProspectPage); 然后就可以了。但是当我从 firbase 获取数据时它应该可以工作。

这是我的 html 代码。

<button id="credentials-button1" ion-button color="stable" block on-click="register()"> Lets go! </button>

你的问题的答案是arrow functions:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

  register(params) {
    ref.orderByChild("ssn").equalTo(1234).on("value", (snapshot) => {
        if(snapshot.val()) {
            this.navCtrl.push(ProspectPage);
        }
    });
  }

注意 (snapshot) => {...} 而不是 function(snapshot) {...}

示例:

this.a = 100;

let arrowFunc = () => {this.a = 150};

function regularFunc() {
this.a = 200;
}

console.log(this.a)

arrowFunc()
console.log(this.a);

regularFunc()
console.log(this.a);

/*
Output

100
150
150
*/

您更正后的代码是:

register(params){
// this.navCtrl.push(ProspectPage); // if i wrote here then it works
//convert to arrow function
 ref.orderByChild("ssn").equalTo(1234).on("value", (snapshot)=> {   
 if(snapshot.val())
    {
    this.navCtrl.push(ProspectPage);
 }
 });
 }