Sura Al Jumaily
Sura Al Jumaily

Reputation: 11

Cannot read property 'push' of undefined when using angular 5 to store data in firebase

This is what I have at the moment:

createPerson(name:any,lname:any,age:any,dept:any){
  this.peopleList.push({
  name: name,
  lname: lname,
  age: age,
  dept: dept
}).then(_person =>{
  this.navCtrl.push(HomePage);
},error=>{console.log(error)});}

Upvotes: 1

Views: 169

Answers (1)

n4nd0_o
n4nd0_o

Reputation: 2998

This syntax seems to be of a promise. A promise can be of type Promise<any[]> but that doesn't mean you can use push() directly.

In addition, assuming this.peopleList is any[], it needs to be initialized before you can do this.peopleList.push().

Finally, it seems you want to do something after this.peopleList receives a new item. You should have an observable/promise and do this in two stages. One where it adds to array and returns the array with the new value and then use either .then or .subscribe to perform the action after the first task is completed.

Edit:

export interface AngularFireList<T> {
      query: DatabaseQuery;
      valueChanges(events?: ChildEvent[]): Observable<T[]>;
      snapshotChanges(events?: ChildEvent[]): Observable<SnapshotAction<T>[]>;
      stateChanges(events?: ChildEvent[]): Observable<SnapshotAction<T>>;
      auditTrail(events?: ChildEvent[]): Observable<SnapshotAction<T>[]>;
      update(item: FirebaseOperation, data: T): Promise<void>;
      set(item: FirebaseOperation, data: T): Promise<void>;
      push(data: T): database.ThenableReference;
      remove(item?: FirebaseOperation): Promise<void>;
    }

This is the AngularFireList interface. From a quick inspection, try something like:

// It subscribes to the changes on the list and perform whatever you need upon change. 
// Put it after you initialized the peopleList
this.peopleList.valueChanges.subscribe((data) => {
   this.navCtrl.push(HomePage);
}, error => console.log(error));

// This is adding a new item on the list, which will trigger the subscription above
this.peopleList.push({
  name: name,
  lname: lname,
  age: age,
  dept: dept
});

Upvotes: 1

Related Questions