错误类型错误:无法读取未定义的属性(读取"推送")



我在下面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));
}
}
}

您似乎还没有在类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');
}

干杯

相关内容

  • 没有找到相关文章

最新更新