如何修复“无法获取未定义或空引用的属性'get'”

时间:2019-08-28 07:50:37

标签: angular typescript ionic-framework ionic4 capacitor

我正在尝试创建应用程序。但是,我不断收到错误消息,说“无法在ProfilePage.prototype.ngOnInit上获取未定义或空引用的属性'get'”。

我正在使用离子4作为框架。当我尝试从主页导航到个人资料页面时发生此错误

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() {}

}

上面的代码应允许用户进入个人资料页面。但是结果是“无法在ProfilePage.prototype.ngOnInit上获取未定义或空引用的属性'get'”

2 个答案:

答案 0 :(得分:1)

您的this.profileService.getUserProfile()可能仅返回null或未定义。使用chrome dev工具的“源”标签进行检查(使用ctrl(cmd)+ p搜索文件)

答案 1 :(得分:0)

尝试这样:

ngOnInit() {

if(this.profileService.getUserProfile() {
    this.profileService
      .getUserProfile()
      .get()
      .then(userProfileSnapshot => {
        this.userProfile = userProfileSnapshot.data();
        this.birthDate = userProfileSnapshot.data().birthDate;
      });
  }
}