Search code examples
angulartypescriptionic2ionic3

ionic 3 "TypeError: this is null"


i am trying to redirect when i am getting data from firebase. if it is null or empty then no need to redirect.

I am trying by using this.navCtrl.push(ProspectPage); but don't know why it is not working it returns an error

TypeError: this is null

Here is my code, please check it and let me know what i am doing wrong here.

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);
    }
   });
  }
 }

see register() there is one comment. If i add this.navCtrl.push(ProspectPage); at the starting of the function then it works. but it should work when i gat the data from firbase.

Here, is my html code.

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

Solution

  • The answer to your question is 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);
            }
        });
      }
    

    Notice the (snapshot) => {...} instead of the function(snapshot) {...}