Ionic3中Firebase数据获取后跳转报错:TypeError: this is null
Hey there! That TypeError: this is null error is almost always a context issue—let's break down why it's happening and how to fix it.
The Root Cause
When you use a regular function as a callback for Firebase operations (like once() or on()), the this inside that callback doesn't point to your Angular component instance anymore. Instead, it refers to the callback's own isolated context, which is why this.navCtrl ends up being null.
Solution 1: Use Arrow Functions (Recommended)
Arrow functions inherit the this context from their surrounding scope—meaning this will correctly reference your component instance. Here's how to adjust your code:
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ProspectPage } from '../prospect/prospect'; import * as firebase from 'firebase'; @Component({ // Your component metadata (selector, templateUrl, etc.) goes here }) export class YourComponent { constructor(public navCtrl: NavController) {} fetchDataAndNavigate() { // Example Firebase data fetch firebase.database().ref('your-target-data-path').once('value', (snapshot) => { const fetchedData = snapshot.val(); // Check if data exists before navigating if (fetchedData && Object.keys(fetchedData).length > 0) { this.navCtrl.push(ProspectPage); } }); } }
Solution 2: Bind this Explicitly
If you prefer using regular functions, you can store the component's this in a variable before the callback, then use that variable inside the callback:
fetchDataAndNavigate() { const componentContext = this; firebase.database().ref('your-target-data-path').once('value', function(snapshot) { const fetchedData = snapshot.val(); if (fetchedData && Object.keys(fetchedData).length > 0) { componentContext.navCtrl.push(ProspectPage); } }); }
Quick Sanity Check
Double-check that you've correctly injected NavController into your component's constructor (like in the examples above). If you skip this step, this.navCtrl would be undefined even without the context mismatch issue.
内容的提问来源于stack exchange,提问作者Harish Mahajan

