I'm following https://www.positronx.io/ionic-firebase-list-tutorial/ which creates a CRUD list app that writes and reads from Firebase. I'm using an Ionic framework with Angular. When I try to write data to firebase, this is the console error I get:
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)
Here is the code in 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,
})
}
and here is 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));
}
}
}
It seems you've not yet defined the property userList
in class UserService
. The tutorial you linked to does it using the getUserList
method, which is being called in the init function of the HomePage
.
The tutorial probably presents the code in a way it's easier to explain, but doesn't always keep the code working, so just follow the tutorial further and you should get your program working in the end.