最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ERROR TypeError: Cannot read properties of undefined (reading 'push') - Stack Overflow

programmeradmin0浏览0评论

I'm following / 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/pat/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));
    }
  }
}

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/pat/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));
    }
  }
}
Share Improve this question edited Feb 2, 2022 at 0:08 Frank van Puffelen 601k85 gold badges890 silver badges860 bronze badges Recognized by Google Cloud Collective asked Jan 22, 2022 at 16:32 empyreanempyrean 751 gold badge2 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2 +25

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.

In the tutorial they used (and they called it in the homepage, which is before the create page ):

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

Which initializes the userList BEFORE calling the createUser

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

Which you seem to use directly

Solution: create the userlist in the constructor as follows:

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

Cheers

发布评论

评论列表(0)

  1. 暂无评论