Pooja Patel
Pooja Patel

Reputation: 89

Cannot read property 'push' of undefined -Angular ,Firebase

here I add my service file code.I want to store data in firebase but I can't get data.I got my data in console but get some error & not push in firebase

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Contact } from './logic/contact';
@Injectable({
  providedIn: 'root'
})
export class DataService {
list: AngularFireList<any>;
createcontact:Contact = new Contact();
  constructor(private firebase:AngularFireDatabase) { } 
  insertdata(contact: Contact) {
// here I get my data in console
        console.log(contact);
        this.list.push({
          name: contact.name,
          email:contact.email,
          phoneno:contact.phoneno,
          notes:contact.notes,
          address:contact.address,
          relation:contact.relation 
        });
      }
  updatedata(contact: Contact) {
    this.list.update(contact._id,{
      name: contact.name,
      email: contact.email,
      phoneno: contact.phoneno,
      notes: contact.notes,
      address: contact.address,
      relation: contact.relation
    });
  }
  }

the error is like

ERROR TypeError: Cannot read property 'push' of undefined

Upvotes: 1

Views: 3118

Answers (2)

compt
compt

Reputation: 80

Just in case someone else encounter this kind of problem, I solved my issue by doing the following:

Define your variable as:

list$: AngularFireList<any[]>;

Then, in the constructor you initialize it as:

this.list$ = firebase.list('/contact'); //your path api

after that, push can be as follows:

this.list$.push([whatever]);

Hope it helps.

Upvotes: 1

Melchia
Melchia

Reputation: 24314

That's not how you push data to firebase. Try the following:

    export class DataService {
    list: AngularFireList<any>;
    createcontact:Contact = new Contact();
      constructor(private firebase:AngularFireDatabase) { } 
      insertdata(contact: Contact) {
    // here I get my data in console
            console.log(contact);
            this.list = this.firebase.list('/lists');
            if (contact) {
             this.list.push({
              name: contact.name,
              email:contact.email,
              phoneno:contact.phoneno,
              notes:contact.notes,
              address:contact.address,
              relation:contact.relation 
            });
          }
        }



updatedata(contact: Contact) {
    if ( contact) {
            this.list.set(contact._id,{
              name: contact.name,
              email: contact.email,
              phoneno: contact.phoneno,
              notes: contact.notes,
              address: contact.address,
              relation: contact.relation
            });
          }
    }
 }

Upvotes: 3

Related Questions