I'm trying to create application. However I keep getting error saying "Unable to get property 'get' of undefined or null reference at ProfilePage.prototype.ngOnInit".
I'm using ionic 4 as my framework. This error occur when I was trying to navigate from my home page to my profile page
HomePage.html:
<ion-header>
<ion-toolbar>
<ion-title>Home</ion-title>
<ion-buttons slot="end">
<ion-button routerLink="/profile">
<ion-icon slot="icon-only" name="person"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
profile.page.ts
import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { AuthService } from '../../services/user/auth.service';
import { ProfileService } from '../../services/user/profile.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.page.html',
styleUrls: ['./profile.page.scss']
})
export class ProfilePage implements OnInit {
public userProfile: any;
public birthDate: Date;
constructor(
private alertCtrl: AlertController,
private authService: AuthService,
private profileService: ProfileService,
private router: Router
) {}
ngOnInit() {
this.profileService
.getUserProfile()
.get()
.then(userProfileSnapshot => {
this.userProfile = userProfileSnapshot.data();
this.birthDate = userProfileSnapshot.data().birthDate;
});
}
......
Homepage.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
constructor() { }
ngOnInit() {}
}
The code above is expected to allow user to go to profile page. however the result were "Unable to get property 'get' of undefined or null reference at ProfilePage.prototype.ngOnInit"
Try like this:
ngOnInit() {
if(this.profileService.getUserProfile() {
this.profileService
.getUserProfile()
.get()
.then(userProfileSnapshot => {
this.userProfile = userProfileSnapshot.data();
this.birthDate = userProfileSnapshot.data().birthDate;
});
}
}