ERROR TypeError: Cannot read properties of undefined (reading 'push')

ERROR TypeError: Cannot read properties of undefined (reading 'push')

我正在关注 https://www.positronx.io/ionic-firebase-list-tutorial/,它创建了一个 CRUD 列表应用程序,可以从 Firebase 写入和读取。我正在使用 Angular 的 Ionic 框架。当我尝试将数据写入 firebase 时,这是我得到的控制台错误:

ERROR TypeError: Cannot read properties of undefined (reading 'push')
    at UserService.createUser (user.service.ts:17:26)
    at MakePage.onFormSubmit (make.page.ts:33:23)
    at MakePage_Template_form_ngSubmit_6_listener (template.html:9:30)
    at executeListenerWithErrorHandling (core.mjs:14963:16)
    at Object.wrapListenerIn_markDirtyAndPreventDefault [as next] (core.mjs:15001:22)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)
    at Subscriber.next (Subscriber.js:49:1)
    at EventEmitter_.next (Subject.js:39:1)

这是user.service.ts中的代码:

import { Injectable } from '@angular/core';
import { User } from './users';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/compat/database';

@Injectable({
  providedIn: 'root'
})

export class UserService {
  userList: AngularFireList<any>;
  userRef: AngularFireObject<any>;

  constructor(private db: AngularFireDatabase) { }

  // Create
  createUser(user: User) {
    return this.userList.push({
      name: user.name,
      email: user.email,
      mobile: user.mobile,
    })
  }

这里是 make.page.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder } from "@angular/forms";
import { UserService } from '../shared/user.service';

@Component({
  selector: 'app-make',
  templateUrl: './make.page.html',
  styleUrls: ['./make.page.scss'],
})

export class MakePage implements OnInit {
  form: FormGroup;

  constructor(
    private apiService: UserService,
    private router: Router,
    public fb: FormBuilder
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      name: [''],
      email: [''],
      mobile: ['']
    })
  }

  onFormSubmit() {
    if (!this.form.valid) {
      return false;
    } else {
      this.apiService.createUser(this.form.value).then(res => {
        this.form.reset();
        this.router.navigate(['/home']);
      })
        .catch(error => console.log(error));
    }
  }
}

您似乎还没有在 class UserService 中定义 属性 userList。您链接到的教程使用 getUserList 方法执行此操作,该方法在 HomePage.

的 init 函数中被调用

本教程可能以更容易解释的方式呈现代码,但并不总是让代码正常工作,因此只需进一步按照本教程进行操作,您最终应该可以让您的程序正常工作。

在他们使用的教程中(他们在主页中调用它,在创建页面之前):

 getUserList() {
    this.userList = this.db.list('/user');
    return this.userList;
  }

在调用 createUser 之前初始化 userList

  createUser(user: User) {
    return this.userList.push({
      name: user.name,
      email: user.email,
      mobile: user.mobile
    })
  }

你好像直接用哪个

解决方法: 在构造函数中创建用户列表,如下所示:

  constructor(private db: AngularFireDatabase) { 
    this.userList = this.db.list('/user');
  }

干杯